The R Project SVN R-packages

Rev

Rev 3855 | Rev 4590 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3855 Rev 4160
1
#include "sqlite_dataframe.h"
1
#include "sqlite_dataframe.h"
2
#include <math.h>
2
#include <math.h>
3
#include "Rmath.h"
3
#include "Rmath.h"
4
 
4
 
5
/****************************************************************************
5
/****************************************************************************
6
 * UTILITY FUNCTIONS
6
 * UTILITY FUNCTIONS
7
 ****************************************************************************/
7
 ****************************************************************************/
8
char *_create_svector1(SEXP name, const char *type, int * _namelen, int protect) {
8
char *_create_svector1(SEXP name, const char *type, int * _namelen, int protect) {
9
    int namelen, res;
9
    int namelen, res;
10
    char *iname = _create_sdf_skeleton1(name, &namelen, protect);
10
    char *iname = _create_sdf_skeleton1(name, &namelen, protect);
11
 
11
 
12
    if (iname == NULL) return NULL;
12
    if (iname == NULL) return NULL;
13
 
13
 
14
    sprintf(g_sql_buf[2], "create table [%s].sdf_data ([row name] text, "
14
    sprintf(g_sql_buf[2], "create table [%s].sdf_data ([row name] text, "
15
            "V1 %s, primary key ([row name]))", iname, type);
15
            "V1 %s, primary key ([row name]))", iname, type);
16
    res = _sqlite_exec(g_sql_buf[2]);
16
    res = _sqlite_exec(g_sql_buf[2]);
17
    _sqlite_error(res);
17
    _sqlite_error(res);
18
 
18
 
19
    if (_namelen != NULL) *_namelen = namelen;
19
    if (_namelen != NULL) *_namelen = namelen;
20
    return iname;
20
    return iname;
21
}
21
}
22
 
22
 
23
SEXP _create_svector_sexp(const char *iname, const char *tblname,
23
SEXP _create_svector_sexp(const char *iname, const char *tblname,
24
        const char *varname, const char *type) {
24
        const char *varname, const char *type) {
25
    SEXP ret, value; int nprotected = 0;
25
    SEXP ret, value; int nprotected = 0;
26
    PROTECT(ret = NEW_LIST(3)); nprotected++;
26
    PROTECT(ret = NEW_LIST(3)); nprotected++;
27
 
27
 
28
    /* set list names */
28
    /* set list names */
29
    PROTECT(value = NEW_CHARACTER(3)); nprotected++;
29
    PROTECT(value = NEW_CHARACTER(3)); nprotected++;
30
    SET_STRING_ELT(value, 0, mkChar("iname"));
30
    SET_STRING_ELT(value, 0, mkChar("iname"));
31
    SET_STRING_ELT(value, 1, mkChar("tblname"));
31
    SET_STRING_ELT(value, 1, mkChar("tblname"));
32
    SET_STRING_ELT(value, 2, mkChar("varname"));
32
    SET_STRING_ELT(value, 2, mkChar("varname"));
33
    SET_NAMES(ret, value);
33
    SET_NAMES(ret, value);
34
 
34
 
35
    /* set list values */
35
    /* set list values */
36
    SET_VECTOR_ELT(ret, 0, mkString(iname));
36
    SET_VECTOR_ELT(ret, 0, mkString(iname));
37
    SET_VECTOR_ELT(ret, 1, mkString(tblname));
37
    SET_VECTOR_ELT(ret, 1, mkString(tblname));
38
    SET_VECTOR_ELT(ret, 2, mkString(varname));
38
    SET_VECTOR_ELT(ret, 2, mkString(varname));
39
 
39
 
40
    /* set sexp class */
40
    /* set sexp class */
41
    SET_CLASS(ret, mkString("sqlite.vector"));
41
    SET_CLASS(ret, mkString("sqlite.vector"));
42
 
42
 
43
    /* set sdf.vector.type */
43
    /* set sdf.vector.type */
44
    SET_SDFVECTORTYPE(ret, mkString(type));
44
    SET_SDFVECTORTYPE(ret, mkString(type));
45
 
45
 
46
    UNPROTECT(nprotected);
46
    UNPROTECT(nprotected);
47
 
47
 
48
    return ret;
48
    return ret;
49
}
49
}
50
 
50
 
51
/* if ret == NULL, 3rd arg is the length of the vector created. otherwise
51
/* if ret == NULL, 3rd arg is the length of the vector to be created. otherwise
52
 * it is the index in the vector ret where we will put the result extracted
52
 * it is the index in the vector ret where we will put the result extracted
53
 * from ret */
53
 * from ret */
54
int _get_vector_index_typed_result(sqlite3_stmt *stmt, SEXP *ret, int idx_or_len) {
54
int _get_vector_index_typed_result(sqlite3_stmt *stmt, SEXP *ret, int colidx,
-
 
55
        int idx_or_len, int *coltype) {
55
    int added = 1;
56
    int added = 1, ctype;
56
    if (*ret == NULL || *ret == R_NilValue) {
57
    if (*ret == NULL || *ret == R_NilValue) {
57
        const char *coltype = sqlite3_column_decltype(stmt, 0);
-
 
58
        if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
58
        if ((ctype = sqlite3_column_type(stmt, colidx)) == SQLITE_NULL) {
59
            added = 0;
59
            added = 0;
60
        }
60
        }
61
        
61
        
62
        if (strcmp(coltype, "text") == 0) {
62
        if (ctype == SQLITE_TEXT) {
63
            PROTECT(*ret = NEW_CHARACTER(idx_or_len));
63
            PROTECT(*ret = NEW_CHARACTER(idx_or_len));
64
            if (added) 
64
            if (added) 
65
                SET_STRING_ELT(*ret, 0, mkChar((char *)sqlite3_column_text(stmt, 0)));
65
                SET_STRING_ELT(*ret, 0, mkChar((char *)sqlite3_column_text(stmt, colidx)));
66
        } else if (strcmp(coltype, "double") == 0) {
66
        } else if (ctype == SQLITE_FLOAT) {
67
            PROTECT(*ret = NEW_NUMERIC(idx_or_len));
67
            PROTECT(*ret = NEW_NUMERIC(idx_or_len));
68
            if (added) REAL(*ret)[0] = sqlite3_column_double(stmt, 0);
68
            if (added) REAL(*ret)[0] = sqlite3_column_double(stmt, colidx);
69
        } else if (strcmp(coltype, "bit") == 0) {
69
        } else if (ctype == SQLITE_INTEGER) {
70
            PROTECT(*ret = NEW_LOGICAL(idx_or_len));
70
            /* sqlite does not differentiate b/w ints & bits, so we have to
71
            if (added) INTEGER(*ret)[0] = sqlite3_column_int(stmt, 0);
71
             * do it ourselves since R distinguishes b/w ints & logicals */
72
        } else if (strcmp(coltype, "integer") == 0 || 
72
            if (strcmp(sqlite3_column_decltype(stmt, colidx), "bit") == 0) {
73
                   strcmp(coltype, "int") == 0) {
73
                ctype = SQLITEDF_BIT; 
-
 
74
                PROTECT(*ret = NEW_LOGICAL(idx_or_len));
74
            /* caller should just copy off the vars level attr for factors */
75
                if (added) LOGICAL(*ret)[0] = sqlite3_column_int(stmt, colidx);
-
 
76
            } else {
75
            PROTECT(*ret = NEW_INTEGER(idx_or_len));
77
                PROTECT(*ret = NEW_INTEGER(idx_or_len));
76
            if (added) INTEGER(*ret)[0] = sqlite3_column_int(stmt, 0);
78
                if (added) INTEGER(*ret)[0] = sqlite3_column_int(stmt, colidx);
-
 
79
            }
77
        } else added = 0;
80
        } else added = 0;
78
 
81
 
79
        UNPROTECT(1);
82
        if (added) UNPROTECT(1);
-
 
83
        *coltype = ctype;
80
    } else if (stmt != NULL) {
84
    } else if (stmt != NULL) {
-
 
85
        int ctype = *coltype;
-
 
86
 
-
 
87
        /* first row must have been NULL so that *coltype was not set */
-
 
88
        if (ctype == SQLITE_NULL) {
81
        const char *coltype = sqlite3_column_decltype(stmt, 0);
89
            ctype = *coltype = sqlite3_column_type(stmt, colidx);
-
 
90
            /* distinguish int or logical */
-
 
91
            if (ctype == SQLITE_INTEGER) 
-
 
92
                ctype = (strcmp(sqlite3_column_decltype(stmt, colidx), "bit") == 0) ?
-
 
93
                    SQLITEDF_BIT : SQLITE_INTEGER;
-
 
94
        }
-
 
95
 
82
        if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
96
        if (sqlite3_column_type(stmt, colidx) == SQLITE_NULL) {
83
            added = 0;
97
            added = 0;
84
        } else if (strcmp(coltype, "text") == 0) {
98
        } else if (ctype == SQLITE_TEXT) {
85
            SET_STRING_ELT(*ret, idx_or_len, 
99
            SET_STRING_ELT(*ret, idx_or_len, 
86
                    mkChar((char *)sqlite3_column_text(stmt, 0)));
100
                    mkChar((char *)sqlite3_column_text(stmt, colidx)));
87
        } else if (strcmp(coltype, "double") == 0) {
101
        } else if (ctype == SQLITE_FLOAT) {
88
            REAL(*ret)[idx_or_len] = sqlite3_column_double(stmt, 0);
102
            REAL(*ret)[idx_or_len] = sqlite3_column_double(stmt, colidx);
89
        } else if (strcmp(coltype, "bit") == 0) {
103
        } else if (ctype == SQLITE_INTEGER) {
90
            INTEGER(*ret)[idx_or_len] = sqlite3_column_int(stmt, 0);
104
            INTEGER(*ret)[idx_or_len] = sqlite3_column_int(stmt, colidx);
91
        } else if (strcmp(coltype, "integer") == 0 ||
105
        } else if (ctype == SQLITEDF_BIT) {
92
                   strcmp(coltype, "int") == 0) {
-
 
93
            /* caller should just copy off the vars level attr for factors */
-
 
94
            INTEGER(*ret)[idx_or_len] = sqlite3_column_int(stmt, 0);
106
            LOGICAL(*ret)[idx_or_len] = sqlite3_column_int(stmt, colidx);
95
        } else added = 0;
107
        } else added = 0;
96
    } else if (stmt == NULL) {
108
    } else if (stmt == NULL) {
97
        const char *coltype = sqlite3_column_decltype(stmt, 0);
109
        /* used when there is no row returned (sqlite3_step(stmt)!= QLITE_ROW),
-
 
110
         * and we just insert NAs in the result */
-
 
111
        ctype = *coltype;
98
        if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
112
        if (ctype == SQLITE_NULL) { 
-
 
113
            /* since stmt == NULL, we can't check its column type */
99
            added = 0;
114
            added = 0;
100
        } else if (strcmp(coltype, "text") == 0) {
115
        } else if (ctype == SQLITE_TEXT) {
101
            SET_STRING_ELT(*ret, idx_or_len, NA_STRING);
116
            SET_STRING_ELT(*ret, idx_or_len, NA_STRING);
102
        } else if (strcmp(coltype, "double") == 0) {
117
        } else if (ctype == SQLITE_FLOAT) {
103
            REAL(*ret)[idx_or_len] = NA_REAL;
118
            REAL(*ret)[idx_or_len] = NA_REAL;
104
        } else if (strcmp(coltype, "bit") == 0 || strcmp(coltype, "integer") == 0 ||
-
 
105
                   strcmp(coltype, "int") == 0) {
119
        } else if (ctype == SQLITE_INTEGER) {
106
            INTEGER(*ret)[idx_or_len] = NA_INTEGER;
120
            INTEGER(*ret)[idx_or_len] = NA_INTEGER;
-
 
121
        } else if (ctype == SQLITEDF_BIT) {
-
 
122
            LOGICAL(*ret)[idx_or_len] = NA_LOGICAL;
107
        } else added = 0;
123
        } else added = 0;
108
    }
124
    }
109
        
125
        
110
    return added;
126
    return added;
111
}
127
}
112
 
128
 
113
/****************************************************************************
129
/****************************************************************************
114
 * SVEC FUNCTIONS
130
 * SVEC FUNCTIONS
115
 ****************************************************************************/
131
 ****************************************************************************/
116
SEXP sdf_get_variable(SEXP sdf, SEXP name) {
132
SEXP sdf_get_variable(SEXP sdf, SEXP name) {
117
    char *iname, *varname, *svec_type = NULL;
133
    char *iname, *varname, *svec_type = NULL;
118
    const char *coltype;
134
    const char *coltype;
119
    int type = -1, res, nprotected = 0;
135
    int type = -1, res, nprotected = 0;
120
    SEXP ret, value;
136
    SEXP ret, value;
121
 
137
 
122
    if (!IS_CHARACTER(name)) {
138
    if (!IS_CHARACTER(name)) {
123
        error("argument is not a string.\n");
139
        error("argument is not a string.\n");
124
    }
140
    }
125
 
141
 
126
    iname = SDF_INAME(sdf);
142
    iname = SDF_INAME(sdf);
127
    varname = CHAR_ELT(name, 0);
143
    varname = CHAR_ELT(name, 0);
128
 
144
 
129
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
145
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
130
 
146
 
131
    /* check if sdf & varname w/in that sdf exists */
147
    /* check if sdf & varname w/in that sdf exists */
132
    sqlite3_stmt *stmt;
148
    sqlite3_stmt *stmt;
133
    sprintf(g_sql_buf[0], "select [%s] from [%s].sdf_data", varname, iname);
149
    sprintf(g_sql_buf[0], "select [%s] from [%s].sdf_data", varname, iname);
134
 
150
 
135
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
151
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
136
 
152
 
137
    if (_sqlite_error(res)) return R_NilValue;
153
    if (_sqlite_error(res)) return R_NilValue;
138
 
154
 
139
    coltype = sqlite3_column_decltype(stmt, 0);
155
    coltype = sqlite3_column_decltype(stmt, 0);
140
    sqlite3_finalize(stmt);
156
    sqlite3_finalize(stmt);
141
    
157
    
142
    PROTECT(ret = NEW_LIST(3)); nprotected++;
158
    PROTECT(ret = NEW_LIST(3)); nprotected++;
143
 
159
 
144
    /* set list names */
160
    /* set list names */
145
    PROTECT(value = NEW_CHARACTER(3)); nprotected++;
161
    PROTECT(value = NEW_CHARACTER(3)); nprotected++;
146
    SET_STRING_ELT(value, 0, mkChar("iname"));
162
    SET_STRING_ELT(value, 0, mkChar("iname"));
147
    SET_STRING_ELT(value, 1, mkChar("tblname"));
163
    SET_STRING_ELT(value, 1, mkChar("tblname"));
148
    SET_STRING_ELT(value, 2, mkChar("varname"));
164
    SET_STRING_ELT(value, 2, mkChar("varname"));
149
    SET_NAMES(ret, value);
165
    SET_NAMES(ret, value);
150
 
166
 
151
    /* set list values */
167
    /* set list values */
152
    SET_VECTOR_ELT(ret, 0, mkString(iname));
168
    SET_VECTOR_ELT(ret, 0, mkString(iname));
153
    SET_VECTOR_ELT(ret, 1, mkString("sdf_data"));
169
    SET_VECTOR_ELT(ret, 1, mkString("sdf_data"));
154
    SET_VECTOR_ELT(ret, 2, mkString(varname));
170
    SET_VECTOR_ELT(ret, 2, mkString(varname));
155
 
171
 
156
    /* set class */
172
    /* set class */
157
    if (strcmp(coltype, "text") == 0) svec_type = "character";
173
    if (strcmp(coltype, "text") == 0) svec_type = "character";
158
    else if (strcmp(coltype, "double") == 0) svec_type = "numeric";
174
    else if (strcmp(coltype, "double") == 0) svec_type = "numeric";
159
    else if (strcmp(coltype, "bit") == 0) svec_type = "logical";
175
    else if (strcmp(coltype, "bit") == 0) svec_type = "logical";
160
    else if (strcmp(coltype, "integer") == 0 || strcmp(coltype, "int") == 0) {
176
    else if (strcmp(coltype, "integer") == 0 || strcmp(coltype, "int") == 0) {
161
        /* determine if int, factor or ordered */
177
        /* determine if int, factor or ordered */
162
        type = _get_factor_levels1(iname, varname, ret);
178
        type = _get_factor_levels1(iname, varname, ret, FALSE);
163
        switch(type) {
179
        switch(type) {
164
            case VAR_INTEGER: svec_type = "integer"; break;
180
            case VAR_INTEGER: svec_type = "integer"; break;
165
            case VAR_FACTOR: svec_type = "factor"; break;
181
            case VAR_FACTOR: svec_type = "factor"; break;
166
            case VAR_ORDERED: svec_type = "ordered";
182
            case VAR_ORDERED: svec_type = "ordered";
167
        }
183
        }
168
 
-
 
169
    }
184
    }
170
 
185
 
171
    SET_CLASS(ret, mkString("sqlite.vector"));
186
    SET_CLASS(ret, mkString("sqlite.vector"));
172
    SET_SDFVECTORTYPE(ret, mkString(svec_type));
187
    SET_SDFVECTORTYPE(ret, mkString(svec_type));
173
 
188
 
174
    UNPROTECT(nprotected);
189
    UNPROTECT(nprotected);
175
    return ret;
190
    return ret;
176
 
191
 
177
}
192
}
178
 
193
 
179
 
194
 
180
SEXP sdf_get_variable_length(SEXP svec) {
195
SEXP sdf_get_variable_length(SEXP svec) {
181
    char *iname = SDF_INAME(svec);
196
    char *iname = SDF_INAME(svec);
182
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
197
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
183
 
198
 
184
    return ScalarInteger(_get_row_count2(iname, 1));
199
    return ScalarInteger(_get_row_count2(iname, 1));
185
}
200
}
186
 
201
 
187
    
202
    
188
SEXP sdf_get_variable_index(SEXP svec, SEXP idx) {
203
SEXP sdf_get_variable_index(SEXP svec, SEXP idx) {
189
    SEXP ret = R_NilValue, tmp;
204
    SEXP ret = R_NilValue, tmp;
190
    char *iname = SDF_INAME(svec), *tblname = SVEC_TBLNAME(svec),
205
    char *iname = SDF_INAME(svec), *tblname = SVEC_TBLNAME(svec),
191
         *varname = SVEC_VARNAME(svec);
206
         *varname = SVEC_VARNAME(svec);
192
    int index, idxlen, i, retlen=0, res;
207
    int index, idxlen, i, retlen=0, res, coltype;
193
    sqlite3_stmt *stmt;
208
    sqlite3_stmt *stmt;
194
 
209
 
195
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
210
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
196
 
211
 
197
    idxlen = LENGTH(idx);
212
    idxlen = LENGTH(idx);
198
    if (idxlen < 1) return ret;
213
    if (idxlen < 1) return ret;
199
 
214
 
200
    sprintf(g_sql_buf[0], "select [%s] from [%s].[%s] limit ?,1",
215
    sprintf(g_sql_buf[0], "select [%s] from [%s].[%s] where rowid=?",
201
            varname, iname, tblname);
216
            varname, iname, tblname);
202
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
217
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
203
    if (_sqlite_error(res)) error("cannot complete request");
218
    if (_sqlite_error(res)) error("cannot complete request");
204
 
219
 
205
    /* get data based on index */
220
    /* get data based on index */
206
    if (IS_NUMERIC(idx)) {
221
    if (IS_NUMERIC(idx)) {
-
 
222
        /* special handling of 1st index, bec this is where we create the
-
 
223
         * SEXP to be used to hold the result */
207
        index = ((int) REAL(idx)[0]) - 1;
224
        index = (int) REAL(idx)[0];
208
        if (index < 0 && idxlen == 1) return ret;
225
        if (index < 1 && idxlen == 1) return ret;
209
 
226
 
210
        if (index >= 0) {
227
        if (index >= 1) {
211
            sqlite3_bind_int(stmt, 1, index);
228
            sqlite3_bind_int(stmt, 1, index);
212
            res = sqlite3_step(stmt);
229
            res = sqlite3_step(stmt);
213
            if (res == SQLITE_ROW) { 
230
            if (res == SQLITE_ROW) { 
214
                retlen = _get_vector_index_typed_result(stmt, &ret, idxlen);
231
                retlen = _get_vector_index_typed_result(stmt, &ret, 0, idxlen, &coltype);
215
            } 
232
            } 
216
        } 
233
        } 
217
        
234
        
218
        if (index < 0 || res != SQLITE_ROW) {
235
        if (index < 1 || res != SQLITE_ROW) {
219
            /* something wrong w/ 1st idx, and it is quietly ignored. we make 
236
            /* something wrong w/ 1st idx, and it is quietly ignored. we make 
220
             * a "dummy" call to setup the SEXP */
237
             * a "dummy" call to setup the SEXP */
221
            sqlite3_reset(stmt);
238
            sqlite3_reset(stmt);
222
            sqlite3_bind_int(stmt, 1, 0);
239
            sqlite3_bind_int(stmt, 1, 0);
223
            res = sqlite3_step(stmt);
240
            res = sqlite3_step(stmt);
224
            if (res == SQLITE_ROW) {
241
            if (res == SQLITE_ROW) {
-
 
242
                /* populate with 1st row. this should be overwritten by 
-
 
243
                 * succeeding calls. if there are no valid result, then 
-
 
244
                 * everything will be removed by _shrink_vector().
-
 
245
                 */
225
                _get_vector_index_typed_result(stmt, &ret, idxlen - 1);
246
                _get_vector_index_typed_result(stmt, &ret, 0, idxlen - 1, &coltype);
226
            }
247
            }
227
            retlen = 0;
248
            retlen = 0;
228
        }
249
        }
229
 
250
 
230
 
251
 
231
        if (idxlen > 1) {
252
        if (idxlen > 1) {
232
            for (i = 1; i < idxlen; i++) {
253
            for (i = 1; i < idxlen; i++) {
233
                index = ((int) REAL(idx)[i]) - 1;
254
                index = (int) REAL(idx)[i];
234
                if (index < 0) continue;
255
                if (index < 1) continue;
235
                sqlite3_reset(stmt);
256
                sqlite3_reset(stmt);
236
                sqlite3_bind_int(stmt, 1, index);
257
                sqlite3_bind_int(stmt, 1, index);
237
                res = sqlite3_step(stmt);
258
                res = sqlite3_step(stmt);
238
                if (res == SQLITE_ROW) {
259
                if (res == SQLITE_ROW) {
239
                    retlen += _get_vector_index_typed_result(stmt, &ret, retlen); 
260
                    retlen += _get_vector_index_typed_result(stmt, &ret, 0, retlen, &coltype); 
240
                } else {
261
                } else {
241
                    retlen += _get_vector_index_typed_result(NULL, &ret, retlen); 
262
                    retlen += _get_vector_index_typed_result(NULL, &ret, 0, retlen, &coltype); 
242
                }
263
                }
243
            }
264
            }
244
        }
265
        }
245
    } else if (IS_INTEGER(idx)) {
266
    } else if (IS_INTEGER(idx)) {
246
        /* similar to REAL (IS_NUMERIC) above, except that we don't have
267
        /* similar to REAL (IS_NUMERIC) above, except that we don't have
247
         * to cast idx to int. can't refactor this out, sucks. */
268
         * to cast idx to int. can't refactor this out, sucks. */
248
        index = INTEGER(idx)[0] - 1;
269
        index = INTEGER(idx)[0];
249
        if (index < 0 && idxlen == 1) return ret;
270
        if (index < 1 && idxlen == 1) return ret;
250
 
271
 
251
        if (index >= 0) {
272
        if (index >= 1) {
252
            sqlite3_bind_int(stmt, 1, index);
273
            sqlite3_bind_int(stmt, 1, index);
253
            res = sqlite3_step(stmt);
274
            res = sqlite3_step(stmt);
254
            if (res == SQLITE_ROW) { 
275
            if (res == SQLITE_ROW) { 
255
                retlen = _get_vector_index_typed_result(stmt, &ret, idxlen);
276
                retlen = _get_vector_index_typed_result(stmt, &ret, 0, idxlen, &coltype);
256
            } 
277
            } 
257
        } 
278
        } 
258
        
279
        
259
        if (index < 0 || res != SQLITE_ROW) {
280
        if (index < 1 || res != SQLITE_ROW) {
260
            /* something wrong w/ 1st idx, and it is quietly ignored. we make 
281
            /* something wrong w/ 1st idx, and it is quietly ignored. we make 
261
             * a "dummy" call to setup the SEXP */
282
             * a "dummy" call to setup the SEXP */
262
            sqlite3_reset(stmt);
283
            sqlite3_reset(stmt);
263
            sqlite3_bind_int(stmt, 1, 0);
284
            sqlite3_bind_int(stmt, 1, 0);
264
            res = sqlite3_step(stmt);
285
            res = sqlite3_step(stmt);
265
            if (res == SQLITE_ROW) {
286
            if (res == SQLITE_ROW) {
266
                _get_vector_index_typed_result(stmt, &ret, idxlen - 1);
287
                _get_vector_index_typed_result(stmt, &ret, 0, idxlen - 1, &coltype);
267
            }
288
            }
268
            retlen = 0;
289
            retlen = 0;
269
        }
290
        }
270
 
291
 
271
        if (idxlen > 1) {
292
        if (idxlen > 1) {
272
            for (i = 1; i < idxlen; i++) {
293
            for (i = 1; i < idxlen; i++) {
273
                index = INTEGER(idx)[i] - 1;
294
                index = INTEGER(idx)[i];
274
                if (index < 0) continue;
295
                if (index < 1) continue;
275
                sqlite3_reset(stmt);
296
                sqlite3_reset(stmt);
276
                sqlite3_bind_int(stmt, 1, index);
297
                sqlite3_bind_int(stmt, 1, index);
277
                res = sqlite3_step(stmt);
298
                res = sqlite3_step(stmt);
278
                if (res == SQLITE_ROW) {
299
                if (res == SQLITE_ROW) {
279
                    retlen += _get_vector_index_typed_result(stmt, &ret, retlen); 
300
                    retlen += _get_vector_index_typed_result(stmt, &ret, 0, retlen, &coltype); 
280
                } else {
301
                } else {
281
                    retlen += _get_vector_index_typed_result(NULL, &ret, retlen);
302
                    retlen += _get_vector_index_typed_result(NULL, &ret, 0, retlen, &coltype);
282
                }
303
                }
283
            }
304
            }
284
        }
305
        }
285
 
306
 
286
    } else if (IS_LOGICAL(idx)) {
307
    } else if (IS_LOGICAL(idx)) {
287
        /* have to deal with recycling */
308
        /* have to deal with recycling */
288
        int veclen = _get_row_count2(iname, 1);
309
        int veclen = _get_row_count2(iname, 1);
289
 
310
 
-
 
311
        /* in this indexing, idx[i] == TRUE is equiv to vector[i]. therefore
-
 
312
         * idxlen <= veclen. if idxlen < veclen, then idx is recycled. */
-
 
313
 
290
        /* find if there is any TRUE element in the vector */
314
        /* find if there is any TRUE element in the vector */
291
        for (i = 0; i < idxlen && i < veclen; i++) {
315
        for (i = 1; i < idxlen && i < veclen; i++) {
292
            if (LOGICAL(idx)[i]) {
316
            if (LOGICAL(idx)[i]) {
293
                sqlite3_bind_int(stmt, 1, i);
317
                sqlite3_bind_int(stmt, 1, i+1);
294
                sqlite3_step(stmt);
318
                sqlite3_step(stmt);
295
                /* there are at least (idxlen-i) TRUE per cycle of the LOGICAL
319
                /* there are at least (idxlen-i) TRUE per cycle of the LOGICAL
296
                 * index. there are at least (veclen/idxlen) cycles (int div).
320
                 * index. there are at least (veclen/idxlen) cycles (int div).
297
                 * at the last cycle, if (veclen%idxlen > 0), there will be
321
                 * at the last cycle, if (veclen%idxlen > 0), there will be
298
                 * at least (veclen%idxlen - i) if veclen%idxlen > i */
322
                 * at least (veclen%idxlen - i) if veclen%idxlen > i */
299
                retlen = (idxlen-i) * (veclen/idxlen);
323
                retlen = (idxlen-i) * (veclen/idxlen);
300
                if (veclen%idxlen > i) retlen += (veclen%idxlen - i);
324
                if (veclen%idxlen > i) retlen += (veclen%idxlen - i);
301
 
325
 
302
                /* create the vector */
326
                /* create the vector */
303
                retlen = _get_vector_index_typed_result(stmt, &ret, retlen);
327
                retlen = _get_vector_index_typed_result(stmt, &ret, 0, retlen, &coltype);
304
                break;
328
                break;
305
            }
329
            }
306
        }
330
        }
307
 
331
 
308
        if (i < idxlen && i < veclen) {
332
        if (i < idxlen && i < veclen) {
309
            for (i++; i < veclen; i++) {
333
            for (i++; i < veclen; i++) {
310
                if (LOGICAL(idx)[i%idxlen]) {
334
                if (LOGICAL(idx)[i%idxlen]) {
311
                    sqlite3_reset(stmt);
335
                    sqlite3_reset(stmt);
312
                    sqlite3_bind_int(stmt, 1, i);
336
                    sqlite3_bind_int(stmt, 1, i+1);
313
                    res = sqlite3_step(stmt);
337
                    res = sqlite3_step(stmt);
314
                    if (res == SQLITE_ROW) {
338
                    if (res == SQLITE_ROW) {
315
                        retlen += _get_vector_index_typed_result(stmt, &ret, retlen);
339
                        retlen += _get_vector_index_typed_result(stmt, &ret, 0, retlen, &coltype);
316
                    } else {
340
                    } else {
317
                        retlen += _get_vector_index_typed_result(NULL, &ret, retlen);
341
                        retlen += _get_vector_index_typed_result(NULL, &ret, 0, retlen, &coltype);
318
                    }
342
                    }
319
                }
343
                }
320
            }
344
            }
321
        }
345
        }
322
    }
346
    }
323
 
347
 
324
    sqlite3_finalize(stmt);
348
    sqlite3_finalize(stmt);
325
 
349
 
326
    if (ret != R_NilValue) {
350
    if (ret != R_NilValue) {
327
        ret = _shrink_vector(ret, retlen);
351
        ret = _shrink_vector(ret, retlen);
328
        tmp = GET_LEVELS(svec);
352
        tmp = GET_LEVELS(svec);
329
        if (tmp != R_NilValue) {
353
        if (tmp != R_NilValue) {
330
            SET_LEVELS(ret, duplicate(tmp));
354
            SET_LEVELS(ret, duplicate(tmp));
331
            if (TEST_SDFVECTORTYPE(svec, "factor")) {
355
            if (TEST_SDFVECTORTYPE(svec, "factor")) {
332
                SET_CLASS(ret, mkString("factor"));
356
                SET_CLASS(ret, mkString("factor"));
333
            } else {
357
            } else {
334
                PROTECT(tmp = NEW_CHARACTER(2));
358
                PROTECT(tmp = NEW_CHARACTER(2));
335
                SET_STRING_ELT(tmp, 0, mkChar("ordered"));
359
                SET_STRING_ELT(tmp, 0, mkChar("ordered"));
336
                SET_STRING_ELT(tmp, 1, mkChar("factor"));
360
                SET_STRING_ELT(tmp, 1, mkChar("factor"));
337
                UNPROTECT(1);
361
                UNPROTECT(1);
338
            }
362
            }
339
        }
363
        }
340
    }
364
    }
341
 
365
 
342
    return ret;
366
    return ret;
343
}
367
}
344
 
368
 
345
/* sqlite.vector.[<- */
369
/* sqlite.vector.[<- */
346
SEXP sdf_set_variable_index(SEXP svec, SEXP idx, SEXP value) {
370
SEXP sdf_set_variable_index(SEXP svec, SEXP idx, SEXP value) {
347
    int idx_len, val_len;
371
    int idx_len, val_len, svec_len, i, res;
-
 
372
    char *iname = SDF_INAME(svec), *tblname = SVEC_TBLNAME(svec),
-
 
373
         *varname = SVEC_VARNAME(svec);
-
 
374
    sqlite3_stmt *stmt;
348
 
375
 
349
    /* match levels if factor or ordered */
376
    /* match levels if factor or ordered */
350
    if (inherits(value, "ordered")) {
377
    if (inherits(value, "ordered")) {
351
    } else if (inherits(value, "factor")) {
378
    } else if (inherits(value, "factor")) {
352
    }
379
    }
353
 
380
 
354
    idx_len = LENGTH(idx);
381
    idx_len = LENGTH(idx);
355
    val_len = LENGTH(value);
382
    val_len = LENGTH(value);
-
 
383
    svec_len = _get_row_count2(iname, TRUE);
-
 
384
 
-
 
385
    if (idx_len % val_len != 0) 
-
 
386
        warning("number of items to replace is not a multiple of replacement length");
-
 
387
 
-
 
388
    sprintf(g_sql_buf[0], "update [%s].[%s] set [%s]=? where rowid=?",
-
 
389
            iname, tblname, varname);
-
 
390
    _sqlite_begin;
-
 
391
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
-
 
392
    if (_sqlite_error(res)) {
-
 
393
        error("cannot complete request");
-
 
394
        _sqlite_commit;
-
 
395
    }
356
 
396
 
357
    if (IS_NUMERIC(idx)) {
397
    if (IS_NUMERIC(idx)) {
-
 
398
        for (i = 0; i < idx_len; i++) {
-
 
399
            /* determine type of svec, cast value to type of it */
-
 
400
            /* value can only be of a single type, because it is a vector! */
-
 
401
            /* if svec is a factor, value is a string, must check with
-
 
402
             * factor levels */
-
 
403
        }
358
    } else if (IS_INTEGER(idx)) {
404
    } else if (IS_INTEGER(idx)) {
359
    } else if (IS_LOGICAL(idx)) {
405
    } else if (IS_LOGICAL(idx)) {
360
    }
406
    }
361
 
407
 
-
 
408
    _sqlite_commit;
362
    return R_NilValue;
409
    return R_NilValue;
363
}
410
}
364
 
411
 
365
SEXP sdf_variable_summary(SEXP svec, SEXP maxsum) {
412
SEXP sdf_variable_summary(SEXP svec, SEXP maxsum) {
366
    char *iname, *tblname, *varname, *type;
413
    char *iname, *tblname, *varname, *type;
367
    sqlite3_stmt *stmt;
414
    sqlite3_stmt *stmt;
368
    int nprotected = 0;
415
    int nprotected = 0;
369
    SEXP ret, names;
416
    SEXP ret, names;
370
 
417
 
371
    iname = SDF_INAME(svec);
418
    iname = SDF_INAME(svec);
372
    tblname = SVEC_TBLNAME(svec);
419
    tblname = SVEC_TBLNAME(svec);
373
    varname = SVEC_VARNAME(svec);
420
    varname = SVEC_VARNAME(svec);
374
    USE_SDF1(iname, TRUE, FALSE);
421
    USE_SDF1(iname, TRUE, FALSE);
375
 
422
 
376
    if ((TEST_SDFVECTORTYPE(svec, "ordered") && ((type = "ordered"))) ||
423
    if ((TEST_SDFVECTORTYPE(svec, "ordered") && ((type = "ordered"))) ||
377
            (TEST_SDFVECTORTYPE(svec, "factor") && ((type = "factor")))) {
424
            (TEST_SDFVECTORTYPE(svec, "factor") && ((type = "factor")))) {
378
        int nrows, i, max_rows = INTEGER(maxsum)[0];
425
        int nrows, i, max_rows = INTEGER(maxsum)[0];
379
 
426
 
380
 
427
 
381
        sprintf(g_sql_buf[0], "[%s].[%s %s]", iname, type, varname);
428
        sprintf(g_sql_buf[0], "[%s].[%s %s]", iname, type, varname);
382
        nrows = _get_row_count2(g_sql_buf[0], FALSE);
429
        nrows = _get_row_count2(g_sql_buf[0], FALSE);
383
        if (nrows <= max_rows) max_rows = nrows;
430
        if (nrows <= max_rows) max_rows = nrows;
384
        else { nrows = max_rows; max_rows--; }
431
        else { nrows = max_rows; max_rows--; }
385
 
432
 
386
        PROTECT(ret = NEW_INTEGER(nrows)); nprotected = 1;
433
        PROTECT(ret = NEW_INTEGER(nrows)); nprotected = 1;
387
        PROTECT(names = NEW_CHARACTER(nrows)); nprotected++;
434
        PROTECT(names = NEW_CHARACTER(nrows)); nprotected++;
388
 
435
 
389
        sprintf(g_sql_buf[0], "select [%s].[%s %s].label, count(*) from "
436
        sprintf(g_sql_buf[0], "select [%s].[%s %s].label, count(*) from "
390
                "[%s].[%s] join [%s].[%s %s] on [%s].[%s].[%s]=[%s].[%s %s].level "
437
                "[%s].[%s] join [%s].[%s %s] on [%s].[%s].[%s]=[%s].[%s %s].level "
391
                "group by [%s].[%s].[%s], [%s].[%s %s].level order by count(*) desc",
438
                "group by [%s].[%s].[%s], [%s].[%s %s].level order by count(*) desc",
392
                iname, type, varname, iname, tblname, iname, type, varname, iname, tblname, varname,
439
                iname, type, varname, iname, tblname, iname, type, varname, iname, tblname, varname,
393
                iname, type, varname, iname, tblname, varname, iname, type, varname);
440
                iname, type, varname, iname, tblname, varname, iname, type, varname);
394
        sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
441
        sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
395
 
442
 
396
        for (i = 0; i < max_rows; i++) {
443
        for (i = 0; i < max_rows; i++) {
397
            sqlite3_step(stmt);
444
            sqlite3_step(stmt);
398
            SET_STRING_ELT(names, i, mkChar((char *)sqlite3_column_text(stmt, 0)));
445
            SET_STRING_ELT(names, i, mkChar((char *)sqlite3_column_text(stmt, 0)));
399
            INTEGER(ret)[i] = sqlite3_column_int(stmt, 1);
446
            INTEGER(ret)[i] = sqlite3_column_int(stmt, 1);
400
        }
447
        }
401
 
448
 
402
        if (nrows > max_rows) {
449
        if (nrows > max_rows) {
403
            int others_sum = 0;
450
            int others_sum = 0;
404
            SET_STRING_ELT(names, nrows-1, mkChar("(Others)"));
451
            SET_STRING_ELT(names, nrows-1, mkChar("(Others)"));
405
            while (sqlite3_step(stmt) == SQLITE_ROW) {
452
            while (sqlite3_step(stmt) == SQLITE_ROW) {
406
                others_sum += sqlite3_column_int(stmt, 1);
453
                others_sum += sqlite3_column_int(stmt, 1);
407
            }
454
            }
408
            INTEGER(ret)[nrows-1] = others_sum;
455
            INTEGER(ret)[nrows-1] = others_sum;
409
        }
456
        }
410
    } else if (TEST_SDFVECTORTYPE(svec, "logical")) {
457
    } else if (TEST_SDFVECTORTYPE(svec, "logical")) {
411
        sprintf(g_sql_buf[0], "select count(*) from "
458
        sprintf(g_sql_buf[0], "select count(*) from "
412
                "[%s].[%s] group by [%s] order by [%s]", iname, tblname, varname, varname);
459
                "[%s].[%s] group by [%s] order by [%s]", iname, tblname, varname, varname);
413
 
460
 
414
        PROTECT(names = NEW_CHARACTER(3)); nprotected = 1;
461
        PROTECT(names = NEW_CHARACTER(3)); nprotected = 1;
415
        PROTECT(ret = NEW_CHARACTER(3)); nprotected++;
462
        PROTECT(ret = NEW_CHARACTER(3)); nprotected++;
416
 
463
 
417
        SET_STRING_ELT(names, 0, mkChar("Mode"));
464
        SET_STRING_ELT(names, 0, mkChar("Mode"));
418
        SET_STRING_ELT(names, 1, mkChar("FALSE"));
465
        SET_STRING_ELT(names, 1, mkChar("FALSE"));
419
        SET_STRING_ELT(names, 2, mkChar("TRUE"));
466
        SET_STRING_ELT(names, 2, mkChar("TRUE"));
420
 
467
 
421
        sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
468
        sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
422
        SET_STRING_ELT(ret, 0, mkChar("logical"));
469
        SET_STRING_ELT(ret, 0, mkChar("logical"));
423
        sqlite3_step(stmt);
470
        sqlite3_step(stmt);
424
        SET_STRING_ELT(ret, 1, mkChar((const char *)sqlite3_column_text(stmt, 0)));
471
        SET_STRING_ELT(ret, 1, mkChar((const char *)sqlite3_column_text(stmt, 0)));
425
        sqlite3_step(stmt);
472
        sqlite3_step(stmt);
426
        SET_STRING_ELT(ret, 2, mkChar((const char *)sqlite3_column_text(stmt, 0)));
473
        SET_STRING_ELT(ret, 2, mkChar((const char *)sqlite3_column_text(stmt, 0)));
427
 
474
 
428
    } else return R_NilValue;
475
    } else return R_NilValue;
429
 
476
 
430
    sqlite3_finalize(stmt);
477
    sqlite3_finalize(stmt);
431
    SET_NAMES(ret, names);
478
    SET_NAMES(ret, names);
432
    SET_CLASS(ret, mkString("table"));
479
    SET_CLASS(ret, mkString("table"));
433
    UNPROTECT(nprotected);
480
    UNPROTECT(nprotected);
434
    return ret;
481
    return ret;
435
}
482
}
436
            
483
            
437
 
484
 
438
/* the global accumulator should be safe if we only do 1 cummulative or
485
/* the global accumulator should be safe if we only do 1 cummulative or
439
 * aggregate at any time. it won't work for stuffs like "select max(col)-min(col)
486
 * aggregate at any time. it won't work for stuffs like "select max(col)-min(col)
440
 * from sdf_data". */
487
 * from sdf_data". */
441
static long double g_accumulator = 0.0; /* accumulator var for cumsum, cumprod, etc. */
488
static long double g_accumulator = 0.0; /* accumulator var for cumsum, cumprod, etc. */
442
static int g_start = 0;            /* flag for start of cummulation */
489
static int g_start = 0;            /* flag for start of cummulation */
443
static int g_narm = 0;             /* for Summary group */
490
static int g_narm = 0;             /* for Summary group */
444
 
491
 
445
void _init_sqlite_function_accumulator() {
492
void _init_sqlite_function_accumulator() {
446
    g_accumulator = 0.0;   /* initialize accumulator */
493
    g_accumulator = 0.0;   /* initialize accumulator */
447
    g_start = 1;           /* flag that we are at start of accumulating */
494
    g_start = 1;           /* flag that we are at start of accumulating */
448
}
495
}
449
 
496
 
450
SEXP sdf_do_variable_math(SEXP func, SEXP vector, SEXP other_args) {
497
SEXP sdf_do_variable_math(SEXP func, SEXP vector, SEXP other_args) {
451
    char *iname, *iname_src, *varname_src, *funcname;
498
    char *iname, *iname_src, *varname_src, *funcname;
452
    int namelen, res;
499
    int namelen, res;
453
    sqlite3_stmt *stmt;
500
    sqlite3_stmt *stmt;
454
 
501
 
455
    /* get data from arguments (function name and sqlite.vector stuffs) */
502
    /* get data from arguments (function name and sqlite.vector stuffs) */
456
    funcname = CHAR_ELT(func, 0);
503
    funcname = CHAR_ELT(func, 0);
457
    iname_src = SDF_INAME(vector);
504
    iname_src = SDF_INAME(vector);
458
    varname_src = SVEC_VARNAME(vector);
505
    varname_src = SVEC_VARNAME(vector);
459
 
506
 
460
    if (!USE_SDF1(iname_src, TRUE, TRUE)) return R_NilValue;
507
    if (!USE_SDF1(iname_src, TRUE, TRUE)) return R_NilValue;
461
 
508
 
462
    /* create a new sdf, with 1 column named V1 */
509
    /* create a new sdf, with 1 column named V1 */
463
    iname = _create_svector1(R_NilValue, "double", &namelen, TRUE);
510
    iname = _create_svector1(R_NilValue, "double", &namelen, TRUE);
464
 
511
 
465
    /* insert into <newsdf>.col, row.names select func(col), rownames */
512
    /* insert into <newsdf>.col, row.names select func(col), rownames */
466
    if (strcmp(funcname, "round") == 0 || strcmp(funcname, "signif") == 0) {
513
    if (strcmp(funcname, "round") == 0 || strcmp(funcname, "signif") == 0) {
467
        double digits = REAL(_getListElement(other_args, "digits"))[0];
514
        double digits = REAL(_getListElement(other_args, "digits"))[0];
468
        sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name], V1) "
515
        sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name], V1) "
469
                "select [row name], %s([%s],?) from [%s].sdf_data", iname, funcname,
516
                "select [row name], %s([%s],?) from [%s].sdf_data", iname, funcname,
470
                varname_src, iname_src);
517
                varname_src, iname_src);
471
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0); 
518
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0); 
472
        if (_sqlite_error(res)) goto vecmath_prepare_error;
519
        if (_sqlite_error(res)) goto vecmath_prepare_error;
473
        res = sqlite3_bind_double(stmt, 1, digits);
520
        res = sqlite3_bind_double(stmt, 1, digits);
474
    } else if (strcmp(funcname, "log") == 0) {
521
    } else if (strcmp(funcname, "log") == 0) {
475
        double base = REAL(_getListElement(other_args, "base"))[0];
522
        double base = REAL(_getListElement(other_args, "base"))[0];
476
        sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name], V1) "
523
        sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name], V1) "
477
                "select [row name], %s([%s],?) from [%s].sdf_data", iname, funcname,
524
                "select [row name], %s([%s],?) from [%s].sdf_data", iname, funcname,
478
                varname_src, iname_src);
525
                varname_src, iname_src);
479
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0); 
526
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0); 
480
        if (_sqlite_error(res)) goto vecmath_prepare_error;
527
        if (_sqlite_error(res)) goto vecmath_prepare_error;
481
        res = sqlite3_bind_double(stmt, 1, base);
528
        res = sqlite3_bind_double(stmt, 1, base);
482
    } else {
529
    } else {
483
        sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name], V1) "
530
        sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name], V1) "
484
                "select [row name], %s([%s]) from [%s].sdf_data", iname, funcname,
531
                "select [row name], %s([%s]) from [%s].sdf_data", iname, funcname,
485
                varname_src, iname_src);
532
                varname_src, iname_src);
486
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0); 
533
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0); 
487
    }
534
    }
488
 
535
 
489
    if (_sqlite_error(res)) {
536
    if (_sqlite_error(res)) {
490
vecmath_prepare_error:
537
vecmath_prepare_error:
491
        sprintf(g_sql_buf[0], "detach %s", iname);
538
        sprintf(g_sql_buf[0], "detach %s", iname);
492
        _sqlite_exec(g_sql_buf[0]);
539
        _sqlite_exec(g_sql_buf[0]);
493
 
540
 
494
        /* we will return a string with the file name, and do file.remove
541
        /* we will return a string with the file name, and do file.remove
495
         * at R */
542
         * at R */
496
        iname[namelen] = '.';
543
        iname[namelen] = '.';
497
        return mkString(iname);
544
        return mkString(iname);
498
    }
545
    }
499
 
546
 
500
    _init_sqlite_function_accumulator();
547
    _init_sqlite_function_accumulator();
501
    sqlite3_step(stmt);
548
    sqlite3_step(stmt);
502
    sqlite3_finalize(stmt);
549
    sqlite3_finalize(stmt);
503
 
550
 
504
    UNUSE_SDF2(iname);
551
    UNUSE_SDF2(iname);
505
    UNUSE_SDF2(iname_src);
552
    UNUSE_SDF2(iname_src);
506
 
553
 
507
    return _create_svector_sexp(iname, "sdf_data", "V1", "numeric");
554
    return _create_svector_sexp(iname, "sdf_data", "V1", "numeric");
508
}
555
}
509
 
556
 
510
SEXP sdf_do_variable_op(SEXP func, SEXP vector, SEXP op2, SEXP arg_reversed) {
557
SEXP sdf_do_variable_op(SEXP func, SEXP vector, SEXP op2, SEXP arg_reversed) {
511
    char *iname = NULL, *iname_src, *varname_src, *funcname;
558
    char *iname = NULL, *iname_src, *varname_src, *funcname;
512
    int res, functype = -1, op2_len, svec_len, i, reversed;
559
    int res, functype = -1, op2_len, svec_len, i, reversed;
513
    sqlite3_stmt *stmt, *stmt2;
560
    sqlite3_stmt *stmt, *stmt2;
514
 
561
 
515
    /* get data from arguments (function name and sqlite.vector stuffs) */
562
    /* get data from arguments (function name and sqlite.vector stuffs) */
516
    funcname = CHAR_ELT(func, 0);
563
    funcname = CHAR_ELT(func, 0);
517
    iname_src = SDF_INAME(vector);
564
    iname_src = SDF_INAME(vector);
518
    varname_src = SVEC_VARNAME(vector);
565
    varname_src = SVEC_VARNAME(vector);
519
    reversed = LOGICAL(arg_reversed)[0];
566
    reversed = LOGICAL(arg_reversed)[0];
520
 
567
 
521
    if (!USE_SDF1(iname_src, TRUE, TRUE)) return R_NilValue;
568
    if (!USE_SDF1(iname_src, TRUE, TRUE)) return R_NilValue;
522
    switch(funcname[0]) {
569
    switch(funcname[0]) {
523
        case '+' :
570
        case '+' :
524
        case '-' :
571
        case '-' :
525
        case '*' :
572
        case '*' :
526
        case '/' :
573
        case '/' :
527
        case '^' :
574
        case '^' :
528
        case '%' : /* %% and %/% */ 
575
        case '%' : /* %% and %/% */ 
529
            functype = 0; break;  /* output is REAL */
576
            functype = 0; break;  /* output is REAL */
530
        case '&' :
577
        case '&' :
531
        case '|' :
578
        case '|' :
532
        case '!' :  /* ! and != */
579
        case '!' :  /* ! and != */
533
            if (funcname[1] == 0) { functype = 1; break; }
580
            if (funcname[1] == 0) { functype = 1; break; }
534
        case '=' :  /* == */
581
        case '=' :  /* == */
535
        case '<' :  /* < and <= */
582
        case '<' :  /* < and <= */
536
        case '>' :  /* > and >= */
583
        case '>' :  /* > and >= */
537
            functype = 2; 
584
            functype = 2; 
538
    }
585
    }
539
 
586
 
540
    svec_len = _get_row_count2(iname_src, 1);
587
    svec_len = _get_row_count2(iname_src, 1);
541
    if (functype == 0 || functype == 2 || (functype == 1 && funcname[0] != '!')) {
588
    if (functype == 0 || functype == 2 || (functype == 1 && funcname[0] != '!')) {
542
        char *insert_fmt_string1c, *insert_fmt_string1s;
589
        char *insert_fmt_string1c, *insert_fmt_string1s;
543
        char *insert_fmt_string2c, *insert_fmt_string2s;
590
        char *insert_fmt_string2c, *insert_fmt_string2s;
544
        int vec_idx, sdf_idx;
591
        int vec_idx, sdf_idx;
545
 
592
 
546
        iname = _create_svector1(R_NilValue, (functype == 0) ? "double" : "bit", NULL, TRUE);
593
        iname = _create_svector1(R_NilValue, (functype == 0) ? "double" : "bit", NULL, TRUE);
547
 
594
 
548
        /* insert_fmt_string prefixes:
595
        /* insert_fmt_string prefixes:
549
         * 1 - op2 is an ordinary vector, op2_len = 1, straightforward insert-select
596
         * 1 - op2 is an ordinary vector, op2_len = 1, straightforward insert-select
550
         * 2 - op2 is an ordinary vector, op2_len > 1, may need recycling, loop both sides
597
         * 2 - op2 is an ordinary vector, op2_len > 1, may need recycling, loop both sides
551
         * s - operator will be printed as string
598
         * s - operator will be printed as string
552
         * c - operator is either INTDIV or RMOD (int division, R modulo). initially, I
599
         * c - operator is either INTDIV or RMOD (int division, R modulo). initially, I
553
         *     thought I could cast both op to int then use / and % of sqlite, which is just
600
         *     thought I could cast both op to int then use / and % of sqlite, which is just
554
         *     the 2nd character of the funcname. however, R's INTDIV and casts to int 
601
         *     the 2nd character of the funcname. however, R's INTDIV and casts to int 
555
         *     after division (e.g. 3.5 %/% 1.5 == 2). RMOD operates on doubles too,
602
         *     after division (e.g. 3.5 %/% 1.5 == 2). RMOD operates on doubles too,
556
         *     which is the remainder of the largest int multiple of "divisor"
603
         *     which is the remainder of the largest int multiple of "divisor"
557
         *     (e.g. 3.5 %% 1.5 = 0.5)
604
         *     (e.g. 3.5 %% 1.5 = 0.5)
558
         */ 
605
         */ 
559
        if (functype == 1) { /* boolean binary operators */
606
        if (functype == 1) { /* boolean binary operators */
560
            if (!reversed) {
607
            if (!reversed) {
561
                insert_fmt_string1s = "insert into [%s].sdf_data "
608
                insert_fmt_string1s = "insert into [%s].sdf_data "
562
                            "select [row name], ([%s] != 0) %s (? != 0) from [%s].sdf_data";
609
                            "select [row name], ([%s] != 0) %s (? != 0) from [%s].sdf_data";
563
            } else {
610
            } else {
564
                insert_fmt_string1s = "insert into [%s].sdf_data "
611
                insert_fmt_string1s = "insert into [%s].sdf_data "
565
                            "select [row name], (? != 0) %s ([%s] != 0) from [%s].sdf_data";
612
                            "select [row name], (? != 0) %s ([%s] != 0) from [%s].sdf_data";
566
            }
613
            }
567
            insert_fmt_string2s = "insert into [%s].sdf_data values(?, (? != 0) %s (? != 0))";
614
            insert_fmt_string2s = "insert into [%s].sdf_data values(?, (? != 0) %s (? != 0))";
568
            /* no need for char version of fmt_string2, since %% only occurs for functype==0 */
615
            /* no need for char version of fmt_string2, since %% only occurs for functype==0 */
569
            insert_fmt_string1c = insert_fmt_string1s;
616
            insert_fmt_string1c = insert_fmt_string1s;
570
            insert_fmt_string2c = insert_fmt_string2s;
617
            insert_fmt_string2c = insert_fmt_string2s;
571
        } else {
618
        } else {
572
            if (!reversed) {
619
            if (!reversed) {
573
                insert_fmt_string1s = "insert into [%s].sdf_data "
620
                insert_fmt_string1s = "insert into [%s].sdf_data "
574
                            "select [row name], [%s] %s ? from [%s].sdf_data";
621
                            "select [row name], [%s] %s ? from [%s].sdf_data";
575
                insert_fmt_string1c = "insert into [%s].sdf_data "
622
                insert_fmt_string1c = "insert into [%s].sdf_data "
576
                            "select [row name], %s([%s],?) from [%s].sdf_data";
623
                            "select [row name], %s([%s],?) from [%s].sdf_data";
577
            } else {
624
            } else {
578
                insert_fmt_string1s = "insert into [%s].sdf_data "
625
                insert_fmt_string1s = "insert into [%s].sdf_data "
579
                            "select [row name], ? %s [%s] from [%s].sdf_data";
626
                            "select [row name], ? %s [%s] from [%s].sdf_data";
580
                insert_fmt_string1c = "insert into [%s].sdf_data "
627
                insert_fmt_string1c = "insert into [%s].sdf_data "
581
                            "select [row name], %s(?,[%s]) from [%s].sdf_data";
628
                            "select [row name], %s(?,[%s]) from [%s].sdf_data";
582
            }
629
            }
583
            /* fmt_string2c format operator from a char, used for %% and %/% */
630
            /* fmt_string2c format operator from a char, used for %% and %/% */
584
            insert_fmt_string2c = "insert into [%s].sdf_data values(?, %s(?,?))";
631
            insert_fmt_string2c = "insert into [%s].sdf_data values(?, %s(?,?))";
585
            insert_fmt_string2s = "insert into [%s].sdf_data values(?, ? %s ?)";
632
            insert_fmt_string2s = "insert into [%s].sdf_data values(?, ? %s ?)";
586
        }
633
        }
587
 
634
 
588
        /* for 2* insert statements, the values below specifies the index of bind().
635
        /* for 2* insert statements, the values below specifies the index of bind().
589
         * if !reversed, then e1 is svec, e2 is anything. otherwise, e2 is the svec */
636
         * if !reversed, then e1 is svec, e2 is anything. otherwise, e2 is the svec */
590
        if (reversed) { sdf_idx = 3; vec_idx = 2; }
637
        if (reversed) { sdf_idx = 3; vec_idx = 2; }
591
        else { sdf_idx = 2; vec_idx = 3; }
638
        else { sdf_idx = 2; vec_idx = 3; }
592
 
639
 
593
        if (IS_NUMERIC(op2)) {
640
        if (IS_NUMERIC(op2)) {
594
            op2_len = LENGTH(op2);
641
            op2_len = LENGTH(op2);
595
 
642
 
596
            if (op2_len == 1) {
643
            if (op2_len == 1) {
597
                if (funcname[0] == '%') {
644
                if (funcname[0] == '%') {
598
                    sprintf(g_sql_buf[2], insert_fmt_string1c, iname, 
645
                    sprintf(g_sql_buf[2], insert_fmt_string1c, iname, 
599
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv", varname_src, iname_src);
646
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv", varname_src, iname_src);
600
                } else {
647
                } else {
601
                    sprintf(g_sql_buf[2], insert_fmt_string1s, iname,
648
                    sprintf(g_sql_buf[2], insert_fmt_string1s, iname,
602
                            varname_src, funcname, iname_src);
649
                            varname_src, funcname, iname_src);
603
                }
650
                }
604
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
651
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
605
                _sqlite_error(res);
652
                _sqlite_error(res);
606
                sqlite3_bind_double(stmt, 1, REAL(op2)[0]);
653
                sqlite3_bind_double(stmt, 1, REAL(op2)[0]);
607
                sqlite3_step(stmt);
654
                sqlite3_step(stmt);
608
                sqlite3_finalize(stmt);
655
                sqlite3_finalize(stmt);
609
            } else if (op2_len <= svec_len) {  /* recycle op2 */
656
            } else if (op2_len <= svec_len) {  /* recycle op2 */
610
                sprintf(g_sql_buf[2], "select [row name], [%s] from [%s].sdf_data",
657
                sprintf(g_sql_buf[2], "select [row name], [%s] from [%s].sdf_data",
611
                        varname_src, iname_src);
658
                        varname_src, iname_src);
612
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
659
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
613
                _sqlite_error(res);
660
                _sqlite_error(res);
614
 
661
 
615
                if (funcname[0] == '%') {
662
                if (funcname[0] == '%') {
616
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname, 
663
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname, 
617
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");  
664
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");  
618
                    _sqlite_begin;
665
                    _sqlite_begin;
619
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
666
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
620
                    _sqlite_error(res);
667
                    _sqlite_error(res);
621
 
668
 
622
                    for (i = 0; i < svec_len; i++) {
669
                    for (i = 0; i < svec_len; i++) {
623
                        sqlite3_step(stmt2);
670
                        sqlite3_step(stmt2);
624
 
671
 
625
                        sqlite3_reset(stmt);
672
                        sqlite3_reset(stmt);
626
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
673
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
627
                        sqlite3_bind_int(stmt, sdf_idx, (int)sqlite3_column_double(stmt2, 1));
674
                        sqlite3_bind_int(stmt, sdf_idx, (int)sqlite3_column_double(stmt2, 1));
628
                        sqlite3_bind_int(stmt, vec_idx, (int)REAL(op2)[i % op2_len]);
675
                        sqlite3_bind_int(stmt, vec_idx, (int)REAL(op2)[i % op2_len]);
629
                        sqlite3_step(stmt);
676
                        sqlite3_step(stmt);
630
                    }
677
                    }
631
                    sqlite3_finalize(stmt);
678
                    sqlite3_finalize(stmt);
632
                    sqlite3_finalize(stmt2);
679
                    sqlite3_finalize(stmt2);
633
                    _sqlite_commit;
680
                    _sqlite_commit;
634
                } else { /* non-integer binary operation */
681
                } else { /* non-integer binary operation */
635
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
682
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
636
                    _sqlite_begin;
683
                    _sqlite_begin;
637
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
684
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
638
                    _sqlite_error(res);
685
                    _sqlite_error(res);
639
 
686
 
640
                    for (i = 0; i < svec_len; i++) {
687
                    for (i = 0; i < svec_len; i++) {
641
                        sqlite3_step(stmt2);
688
                        sqlite3_step(stmt2);
642
 
689
 
643
                        sqlite3_reset(stmt);
690
                        sqlite3_reset(stmt);
644
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
691
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
645
                        sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
692
                        sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
646
                        sqlite3_bind_double(stmt, vec_idx, REAL(op2)[i % op2_len]);
693
                        sqlite3_bind_double(stmt, vec_idx, REAL(op2)[i % op2_len]);
647
                        sqlite3_step(stmt);
694
                        sqlite3_step(stmt);
648
                    }
695
                    }
649
                    sqlite3_finalize(stmt);
696
                    sqlite3_finalize(stmt);
650
                    sqlite3_finalize(stmt2);
697
                    sqlite3_finalize(stmt2);
651
                    _sqlite_commit;
698
                    _sqlite_commit;
652
                }
699
                }
653
            } else { /* op2_len > svec_len, recycle svec */
700
            } else { /* op2_len > svec_len, recycle svec */
654
                sprintf(g_sql_buf[1], "select [%s] from [%s].sdf_data",
701
                sprintf(g_sql_buf[1], "select [%s] from [%s].sdf_data",
655
                        varname_src, iname_src);
702
                        varname_src, iname_src);
656
 
703
 
657
                if (funcname[0] == '%') {
704
                if (funcname[0] == '%') {
658
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname, 
705
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname, 
659
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
706
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
660
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
707
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
661
                    _sqlite_error(res);
708
                    _sqlite_error(res);
662
                } else {
709
                } else {
663
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
710
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
664
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
711
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
665
                    _sqlite_error(res);
712
                    _sqlite_error(res);
666
                }
713
                }
667
 
714
 
668
                i = 0; _sqlite_begin;
715
                i = 0; _sqlite_begin;
669
                while (i < op2_len) {
716
                while (i < op2_len) {
670
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
717
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
671
                    _sqlite_error(res);
718
                    _sqlite_error(res);
672
 
719
 
673
                    if (funcname[0] == '%') {
720
                    if (funcname[0] == '%') {
674
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
721
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
675
                            sqlite3_step(stmt2);
722
                            sqlite3_step(stmt2);
676
 
723
 
677
                            sqlite3_reset(stmt);
724
                            sqlite3_reset(stmt);
678
                            /* simplify my life, just use ints for row names so that we
725
                            /* simplify my life, just use ints for row names so that we
679
                             * don't have to worry about duplicates */
726
                             * don't have to worry about duplicates */
680
                            sqlite3_bind_int(stmt, 1, i); 
727
                            sqlite3_bind_int(stmt, 1, i); 
681
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 1));
728
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 1));
682
                            sqlite3_bind_int(stmt, vec_idx, (int)REAL(op2)[i % op2_len]);
729
                            sqlite3_bind_int(stmt, vec_idx, (int)REAL(op2)[i % op2_len]);
683
                            sqlite3_step(stmt);
730
                            sqlite3_step(stmt);
684
                        }
731
                        }
685
                    } else {
732
                    } else {
686
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
733
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
687
                            sqlite3_step(stmt2);
734
                            sqlite3_step(stmt2);
688
 
735
 
689
                            sqlite3_reset(stmt);
736
                            sqlite3_reset(stmt);
690
                            sqlite3_bind_int(stmt, 1, i);
737
                            sqlite3_bind_int(stmt, 1, i);
691
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
738
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
692
                            sqlite3_bind_double(stmt, vec_idx, REAL(op2)[i % op2_len]);
739
                            sqlite3_bind_double(stmt, vec_idx, REAL(op2)[i % op2_len]);
693
                            sqlite3_step(stmt);
740
                            sqlite3_step(stmt);
694
                        }
741
                        }
695
                    }
742
                    }
696
 
743
 
697
                    /* recycle on svec if we loop again */
744
                    /* recycle on svec if we loop again */
698
                    sqlite3_finalize(stmt2);
745
                    sqlite3_finalize(stmt2);
699
                }
746
                }
700
 
747
 
701
                sqlite3_finalize(stmt);
748
                sqlite3_finalize(stmt);
702
                _sqlite_commit;
749
                _sqlite_commit;
703
            }
750
            }
704
 
751
 
705
        } else if (IS_INTEGER(op2) || IS_LOGICAL(op2)) { /* I N T E G E R */
752
        } else if (IS_INTEGER(op2) || IS_LOGICAL(op2)) { /* I N T E G E R */
706
            /* we are taking advantage of the fact that logicals are stored as int.
753
            /* we are taking advantage of the fact that logicals are stored as int.
707
             * if this becomes untrue in the future, then this is a bug */
754
             * if this becomes untrue in the future, then this is a bug */
708
            /* we are binding double because ___ (?) */
755
            /* we are binding double because ___ (?) */
709
            op2_len = LENGTH(op2);
756
            op2_len = LENGTH(op2);
710
 
757
 
711
            if (op2_len == 1) {
758
            if (op2_len == 1) {
712
                if (funcname[0] == '%') {
759
                if (funcname[0] == '%') {
713
                    sprintf(g_sql_buf[2], insert_fmt_string1c, iname, 
760
                    sprintf(g_sql_buf[2], insert_fmt_string1c, iname, 
714
                            varname_src, (funcname[1] == '%') ? "r_mod" : "r_intdiv", iname_src);
761
                            varname_src, (funcname[1] == '%') ? "r_mod" : "r_intdiv", iname_src);
715
                } else {
762
                } else {
716
                    sprintf(g_sql_buf[2], insert_fmt_string1s, iname,
763
                    sprintf(g_sql_buf[2], insert_fmt_string1s, iname,
717
                            varname_src, funcname, iname_src);
764
                            varname_src, funcname, iname_src);
718
                }
765
                }
719
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
766
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
720
                _sqlite_error(res);
767
                _sqlite_error(res);
721
                sqlite3_bind_double(stmt, 1, (double)INTEGER(op2)[0]);
768
                sqlite3_bind_double(stmt, 1, (double)INTEGER(op2)[0]);
722
                sqlite3_step(stmt);
769
                sqlite3_step(stmt);
723
            } else if (op2_len <= svec_len) {
770
            } else if (op2_len <= svec_len) {
724
                sprintf(g_sql_buf[2], "select [row name], [%s] from [%s].sdf_data",
771
                sprintf(g_sql_buf[2], "select [row name], [%s] from [%s].sdf_data",
725
                        varname_src, iname_src);
772
                        varname_src, iname_src);
726
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
773
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
727
                _sqlite_error(res);
774
                _sqlite_error(res);
728
 
775
 
729
                if (funcname[0] == '%') {
776
                if (funcname[0] == '%') {
730
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname, 
777
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname, 
731
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
778
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
732
                    _sqlite_begin;
779
                    _sqlite_begin;
733
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
780
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
734
                    _sqlite_error(res);
781
                    _sqlite_error(res);
735
 
782
 
736
                    for (i = 0; i < svec_len; i++) {
783
                    for (i = 0; i < svec_len; i++) {
737
                        sqlite3_step(stmt2);
784
                        sqlite3_step(stmt2);
738
 
785
 
739
                        sqlite3_reset(stmt);
786
                        sqlite3_reset(stmt);
740
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
787
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
741
                        sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 1));
788
                        sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 1));
742
                        sqlite3_bind_int(stmt, vec_idx, INTEGER(op2)[i % op2_len]);
789
                        sqlite3_bind_int(stmt, vec_idx, INTEGER(op2)[i % op2_len]);
743
                        sqlite3_step(stmt);
790
                        sqlite3_step(stmt);
744
                    }
791
                    }
745
                    sqlite3_finalize(stmt);
792
                    sqlite3_finalize(stmt);
746
                    sqlite3_finalize(stmt2);
793
                    sqlite3_finalize(stmt2);
747
                    _sqlite_commit;
794
                    _sqlite_commit;
748
                } else {
795
                } else {
749
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
796
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
750
                    _sqlite_begin;
797
                    _sqlite_begin;
751
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
798
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
752
                    _sqlite_error(res);
799
                    _sqlite_error(res);
753
 
800
 
754
                    for (i = 0; i < svec_len; i++) {
801
                    for (i = 0; i < svec_len; i++) {
755
                        sqlite3_step(stmt2);
802
                        sqlite3_step(stmt2);
756
 
803
 
757
                        sqlite3_reset(stmt);
804
                        sqlite3_reset(stmt);
758
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
805
                        sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
759
                        sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
806
                        sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
760
                        sqlite3_bind_double(stmt, vec_idx, (double)INTEGER(op2)[i % op2_len]);
807
                        sqlite3_bind_double(stmt, vec_idx, (double)INTEGER(op2)[i % op2_len]);
761
                        sqlite3_step(stmt);
808
                        sqlite3_step(stmt);
762
                    }
809
                    }
763
                    sqlite3_finalize(stmt);
810
                    sqlite3_finalize(stmt);
764
                    sqlite3_finalize(stmt2);
811
                    sqlite3_finalize(stmt2);
765
                    _sqlite_commit;
812
                    _sqlite_commit;
766
                }
813
                }
767
            } else {
814
            } else {
768
                sprintf(g_sql_buf[1], "select [%s] from [%s].sdf_data",
815
                sprintf(g_sql_buf[1], "select [%s] from [%s].sdf_data",
769
                        varname_src, iname_src);
816
                        varname_src, iname_src);
770
 
817
 
771
                if (funcname[0] == '%') {
818
                if (funcname[0] == '%') {
772
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname,
819
                    sprintf(g_sql_buf[2], insert_fmt_string2c, iname,
773
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
820
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
774
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
821
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
775
                    _sqlite_error(res);
822
                    _sqlite_error(res);
776
                } else {
823
                } else {
777
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
824
                    sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
778
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
825
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
779
                    _sqlite_error(res);
826
                    _sqlite_error(res);
780
                }
827
                }
781
               
828
               
782
                i = 0; _sqlite_begin; 
829
                i = 0; _sqlite_begin; 
783
                while (i < op2_len) {
830
                while (i < op2_len) {
784
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
831
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
785
                    _sqlite_error(res);
832
                    _sqlite_error(res);
786
 
833
 
787
                    if (funcname[0] == '%') {
834
                    if (funcname[0] == '%') {
788
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
835
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
789
                            sqlite3_step(stmt2);
836
                            sqlite3_step(stmt2);
790
 
837
 
791
                            sqlite3_reset(stmt);
838
                            sqlite3_reset(stmt);
792
                            /* simplify my life, just use ints for row names so that we
839
                            /* simplify my life, just use ints for row names so that we
793
                             * don't have to worry about duplicates */
840
                             * don't have to worry about duplicates */
794
                            sqlite3_bind_int(stmt, 1, i); 
841
                            sqlite3_bind_int(stmt, 1, i); 
795
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 1));
842
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 1));
796
                            sqlite3_bind_int(stmt, vec_idx, INTEGER(op2)[i % op2_len]);
843
                            sqlite3_bind_int(stmt, vec_idx, INTEGER(op2)[i % op2_len]);
797
                            sqlite3_step(stmt);
844
                            sqlite3_step(stmt);
798
                        }
845
                        }
799
                    } else {
846
                    } else {
800
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
847
                        for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
801
                            sqlite3_step(stmt2);
848
                            sqlite3_step(stmt2);
802
 
849
 
803
                            sqlite3_reset(stmt);
850
                            sqlite3_reset(stmt);
804
                            sqlite3_bind_int(stmt, 1, i);
851
                            sqlite3_bind_int(stmt, 1, i);
805
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
852
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 1));
806
                            sqlite3_bind_double(stmt, vec_idx, (double)INTEGER(op2)[i % op2_len]);
853
                            sqlite3_bind_double(stmt, vec_idx, (double)INTEGER(op2)[i % op2_len]);
807
                            sqlite3_step(stmt);
854
                            sqlite3_step(stmt);
808
                        }
855
                        }
809
                    }
856
                    }
810
 
857
 
811
                    /* recycle on svec if we loop again */
858
                    /* recycle on svec if we loop again */
812
                    sqlite3_finalize(stmt2);
859
                    sqlite3_finalize(stmt2);
813
                }
860
                }
814
                sqlite3_finalize(stmt);
861
                sqlite3_finalize(stmt);
815
                _sqlite_commit;
862
                _sqlite_commit;
816
            }
863
            }
817
 
864
 
818
        } else if (IS_CHARACTER(op2)) {
865
        } else if (IS_CHARACTER(op2)) {
819
            if (functype != 2) error("not supported");
866
            if (functype != 2) error("not supported");
820
 
867
 
821
            op2_len = LENGTH(op2);
868
            op2_len = LENGTH(op2);
822
 
869
 
823
            if (op2_len == 1) {
870
            if (op2_len == 1) {
824
                sprintf(g_sql_buf[2], insert_fmt_string1s, iname,
871
                sprintf(g_sql_buf[2], insert_fmt_string1s, iname,
825
                            varname_src, funcname, iname_src);
872
                            varname_src, funcname, iname_src);
826
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
873
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
827
                _sqlite_error(res);
874
                _sqlite_error(res);
828
                sqlite3_bind_text(stmt, 1, CHAR_ELT(op2, 0), -1, SQLITE_STATIC);
875
                sqlite3_bind_text(stmt, 1, CHAR_ELT(op2, 0), -1, SQLITE_STATIC);
829
                sqlite3_step(stmt);
876
                sqlite3_step(stmt);
830
            } else if (op2_len <= svec_len) {
877
            } else if (op2_len <= svec_len) {
831
                sprintf(g_sql_buf[2], "select [row name], [%s] from [%s].sdf_data",
878
                sprintf(g_sql_buf[2], "select [row name], [%s] from [%s].sdf_data",
832
                        varname_src, iname_src);
879
                        varname_src, iname_src);
833
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
880
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
834
                _sqlite_error(res);
881
                _sqlite_error(res);
835
 
882
 
836
                sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
883
                sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
837
                _sqlite_begin;
884
                _sqlite_begin;
838
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
885
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
839
                _sqlite_error(res);
886
                _sqlite_error(res);
840
 
887
 
841
                for (i = 0; i < svec_len; i++) {
888
                for (i = 0; i < svec_len; i++) {
842
                    sqlite3_step(stmt2);
889
                    sqlite3_step(stmt2);
843
 
890
 
844
                    sqlite3_reset(stmt);
891
                    sqlite3_reset(stmt);
845
                    sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
892
                    sqlite3_bind_text(stmt, 1, (char *)sqlite3_column_text(stmt2, 0), -1, SQLITE_STATIC);
846
                    sqlite3_bind_text(stmt, sdf_idx, (char *)sqlite3_column_text(stmt2, 1), -1, SQLITE_STATIC);
893
                    sqlite3_bind_text(stmt, sdf_idx, (char *)sqlite3_column_text(stmt2, 1), -1, SQLITE_STATIC);
847
                    sqlite3_bind_text(stmt, vec_idx, CHAR_ELT(op2, i % op2_len), -1 , SQLITE_STATIC);
894
                    sqlite3_bind_text(stmt, vec_idx, CHAR_ELT(op2, i % op2_len), -1 , SQLITE_STATIC);
848
                    sqlite3_step(stmt);
895
                    sqlite3_step(stmt);
849
                }
896
                }
850
                sqlite3_finalize(stmt2);
897
                sqlite3_finalize(stmt2);
851
                _sqlite_commit;
898
                _sqlite_commit;
852
            } else {
899
            } else {
853
                sprintf(g_sql_buf[1], "select [%s] from [%s].sdf_data",
900
                sprintf(g_sql_buf[1], "select [%s] from [%s].sdf_data",
854
                        varname_src, iname_src);
901
                        varname_src, iname_src);
855
 
902
 
856
                sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
903
                sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
857
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
904
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
858
                _sqlite_error(res);
905
                _sqlite_error(res);
859
               
906
               
860
                i = 0; _sqlite_begin; 
907
                i = 0; _sqlite_begin; 
861
                while (i < op2_len) {
908
                while (i < op2_len) {
862
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
909
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
863
                    _sqlite_error(res);
910
                    _sqlite_error(res);
864
 
911
 
865
                    for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
912
                    for ( ; i < op2_len && sqlite3_step(stmt) == SQLITE_ROW ; i++) {
866
                        sqlite3_step(stmt2);
913
                        sqlite3_step(stmt2);
867
 
914
 
868
                        sqlite3_reset(stmt);
915
                        sqlite3_reset(stmt);
869
                        sqlite3_bind_int(stmt, 1, i);
916
                        sqlite3_bind_int(stmt, 1, i);
870
                        sqlite3_bind_text(stmt, sdf_idx, (char *)sqlite3_column_text(stmt2, 1), -1, SQLITE_STATIC);
917
                        sqlite3_bind_text(stmt, sdf_idx, (char *)sqlite3_column_text(stmt2, 1), -1, SQLITE_STATIC);
871
                        sqlite3_bind_text(stmt, vec_idx, CHAR_ELT(op2, i % op2_len), -1 , SQLITE_STATIC);
918
                        sqlite3_bind_text(stmt, vec_idx, CHAR_ELT(op2, i % op2_len), -1 , SQLITE_STATIC);
872
                        sqlite3_step(stmt);
919
                        sqlite3_step(stmt);
873
                    }
920
                    }
874
 
921
 
875
                    /* recycle on svec if we loop again */
922
                    /* recycle on svec if we loop again */
876
                    sqlite3_finalize(stmt2);
923
                    sqlite3_finalize(stmt2);
877
                }
924
                }
878
                sqlite3_finalize(stmt);
925
                sqlite3_finalize(stmt);
879
                _sqlite_commit;
926
                _sqlite_commit;
880
            }
927
            }
881
        
928
        
882
        } else if (inherits(op2, "sqlite.vector")) { 
929
        } else if (inherits(op2, "sqlite.vector")) { 
883
            /* op2 is surely not a factor, as handled by the R wrapper */
930
            /* op2 is surely not a factor, as handled by the R wrapper */
884
            /* even though it is impossible for reversed to be FALSE, still use
931
            /* even though it is impossible for reversed to be FALSE, still use
885
             * sdf_idx and vec_idx so that code would be less confusing */
932
             * sdf_idx and vec_idx so that code would be less confusing */
886
            char *iname_op2, *varname_op2;
933
            char *iname_op2, *varname_op2;
887
            sqlite3_stmt *stmt3;
934
            sqlite3_stmt *stmt3;
888
            iname_op2 = SDF_INAME(op2);
935
            iname_op2 = SDF_INAME(op2);
889
            varname_op2 = SVEC_VARNAME(op2);
936
            varname_op2 = SVEC_VARNAME(op2);
890
 
937
 
891
            if (!USE_SDF1(iname_op2, TRUE, TRUE)) {
938
            if (!USE_SDF1(iname_op2, TRUE, TRUE)) {
892
                /* delete created sqlite.vector */
939
                /* delete created sqlite.vector */
893
                warning("detaching created result SDF %s\n", iname);
940
                warning("detaching created result SDF %s\n", iname);
894
                sdf_detach_sdf(mkString(iname));
941
                sdf_detach_sdf(mkString(iname));
895
                return R_NilValue;
942
                return R_NilValue;
896
            }
943
            }
897
            _sqlite_begin;
944
            _sqlite_begin;
898
 
945
 
899
            op2_len = _get_row_count2(iname_op2, 1);
946
            op2_len = _get_row_count2(iname_op2, 1);
900
            
947
            
901
            sprintf(g_sql_buf[2], "select [%s] from [%s].sdf_data", varname_src, iname_src);
948
            sprintf(g_sql_buf[2], "select [%s] from [%s].sdf_data", varname_src, iname_src);
902
            res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
949
            res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, 0);
903
            _sqlite_error(res);
950
            _sqlite_error(res);
904
 
951
 
905
            sprintf(g_sql_buf[2], "select [%s] from [%s].sdf_data", varname_op2, iname_op2);
952
            sprintf(g_sql_buf[2], "select [%s] from [%s].sdf_data", varname_op2, iname_op2);
906
            res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt3, 0);
953
            res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt3, 0);
907
            _sqlite_error(res);
954
            _sqlite_error(res);
908
 
955
 
909
            if (funcname[0] == '%') {
956
            if (funcname[0] == '%') {
910
                sprintf(g_sql_buf[2], insert_fmt_string2c, iname,
957
                sprintf(g_sql_buf[2], insert_fmt_string2c, iname,
911
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
958
                            (funcname[1] == '%') ? "r_mod" : "r_intdiv");
912
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
959
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
913
                _sqlite_error(res);
960
                _sqlite_error(res);
914
 
961
 
915
                if (svec_len == op2_len) {
962
                if (svec_len == op2_len) {
916
                    for (i = 0; i < svec_len; i++) {
963
                    for (i = 0; i < svec_len; i++) {
917
                        sqlite3_step(stmt2); sqlite3_step(stmt3);
964
                        sqlite3_step(stmt2); sqlite3_step(stmt3);
918
 
965
 
919
                        sqlite3_reset(stmt);
966
                        sqlite3_reset(stmt);
920
                        sqlite3_bind_int(stmt, 1, i);
967
                        sqlite3_bind_int(stmt, 1, i);
921
                        sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 0));
968
                        sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 0));
922
                        sqlite3_bind_int(stmt, vec_idx, sqlite3_column_int(stmt3, 0));
969
                        sqlite3_bind_int(stmt, vec_idx, sqlite3_column_int(stmt3, 0));
923
                        sqlite3_step(stmt);
970
                        sqlite3_step(stmt);
924
                    }
971
                    }
925
                } else if (svec_len < op2_len) {
972
                } else if (svec_len < op2_len) {
926
                    i = 0;
973
                    i = 0;
927
                    while (i < op2_len) {
974
                    while (i < op2_len) {
928
                        for ( ; sqlite3_step(stmt2) == SQLITE_ROW && i < op2_len; i++) {
975
                        for ( ; sqlite3_step(stmt2) == SQLITE_ROW && i < op2_len; i++) {
929
                            sqlite3_step(stmt3);
976
                            sqlite3_step(stmt3);
930
 
977
 
931
                            sqlite3_reset(stmt);
978
                            sqlite3_reset(stmt);
932
                            sqlite3_bind_int(stmt, 1, i);
979
                            sqlite3_bind_int(stmt, 1, i);
933
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 0));
980
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 0));
934
                            sqlite3_bind_int(stmt, vec_idx, sqlite3_column_int(stmt3, 0));
981
                            sqlite3_bind_int(stmt, vec_idx, sqlite3_column_int(stmt3, 0));
935
                            sqlite3_step(stmt);
982
                            sqlite3_step(stmt);
936
                        }
983
                        }
937
                        sqlite3_reset(stmt2);
984
                        sqlite3_reset(stmt2);
938
                    }
985
                    }
939
                } else {
986
                } else {
940
                    i = 0;
987
                    i = 0;
941
                    while (i < svec_len) {
988
                    while (i < svec_len) {
942
                        for ( ; sqlite3_step(stmt3) == SQLITE_ROW && i < svec_len; i++) {
989
                        for ( ; sqlite3_step(stmt3) == SQLITE_ROW && i < svec_len; i++) {
943
                            sqlite3_step(stmt2);
990
                            sqlite3_step(stmt2);
944
 
991
 
945
                            sqlite3_reset(stmt);
992
                            sqlite3_reset(stmt);
946
                            sqlite3_bind_int(stmt, 1, i);
993
                            sqlite3_bind_int(stmt, 1, i);
947
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 0));
994
                            sqlite3_bind_int(stmt, sdf_idx, sqlite3_column_int(stmt2, 0));
948
                            sqlite3_bind_int(stmt, vec_idx, sqlite3_column_int(stmt3, 0));
995
                            sqlite3_bind_int(stmt, vec_idx, sqlite3_column_int(stmt3, 0));
949
                            sqlite3_step(stmt);
996
                            sqlite3_step(stmt);
950
                        }
997
                        }
951
                        sqlite3_reset(stmt3);
998
                        sqlite3_reset(stmt3);
952
                    }
999
                    }
953
                }
1000
                }
954
                _sqlite_commit;
1001
                _sqlite_commit;
955
            } else { /* not an integer op %% or %/% */
1002
            } else { /* not an integer op %% or %/% */
956
                sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
1003
                sprintf(g_sql_buf[2], insert_fmt_string2s, iname, funcname);
957
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
1004
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
958
                _sqlite_error(res);
1005
                _sqlite_error(res);
959
 
1006
 
960
                if (svec_len == op2_len) {
1007
                if (svec_len == op2_len) {
961
                    for (i = 0; i < svec_len; i++) {
1008
                    for (i = 0; i < svec_len; i++) {
962
                        sqlite3_step(stmt2); sqlite3_step(stmt3);
1009
                        sqlite3_step(stmt2); sqlite3_step(stmt3);
963
 
1010
 
964
                        sqlite3_reset(stmt);
1011
                        sqlite3_reset(stmt);
965
                        sqlite3_bind_int(stmt, 1, i);
1012
                        sqlite3_bind_int(stmt, 1, i);
966
                        sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 0));
1013
                        sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 0));
967
                        sqlite3_bind_double(stmt, vec_idx, sqlite3_column_double(stmt3, 0));
1014
                        sqlite3_bind_double(stmt, vec_idx, sqlite3_column_double(stmt3, 0));
968
                        sqlite3_step(stmt);
1015
                        sqlite3_step(stmt);
969
                    }
1016
                    }
970
                } else if (svec_len < op2_len) { /* recycle svec */
1017
                } else if (svec_len < op2_len) { /* recycle svec */
971
                    i = 0;
1018
                    i = 0;
972
                    while (i < op2_len) {
1019
                    while (i < op2_len) {
973
                        for ( ; sqlite3_step(stmt2) == SQLITE_ROW && i < op2_len; i++) {
1020
                        for ( ; sqlite3_step(stmt2) == SQLITE_ROW && i < op2_len; i++) {
974
                            sqlite3_step(stmt3);
1021
                            sqlite3_step(stmt3);
975
 
1022
 
976
                            sqlite3_reset(stmt);
1023
                            sqlite3_reset(stmt);
977
                            sqlite3_bind_int(stmt, 1, i);
1024
                            sqlite3_bind_int(stmt, 1, i);
978
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 0));
1025
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 0));
979
                            sqlite3_bind_double(stmt, vec_idx, sqlite3_column_double(stmt3, 0));
1026
                            sqlite3_bind_double(stmt, vec_idx, sqlite3_column_double(stmt3, 0));
980
                            sqlite3_step(stmt);
1027
                            sqlite3_step(stmt);
981
                        }
1028
                        }
982
                        sqlite3_reset(stmt2);
1029
                        sqlite3_reset(stmt2);
983
                    }
1030
                    }
984
                } else { /* svec_len > op2_len, recycle op2 */
1031
                } else { /* svec_len > op2_len, recycle op2 */
985
                    i = 0;
1032
                    i = 0;
986
                    while (i < svec_len) {
1033
                    while (i < svec_len) {
987
                        for ( ; sqlite3_step(stmt3) == SQLITE_ROW && i < svec_len; i++) {
1034
                        for ( ; sqlite3_step(stmt3) == SQLITE_ROW && i < svec_len; i++) {
988
                            sqlite3_step(stmt2);
1035
                            sqlite3_step(stmt2);
989
 
1036
 
990
                            sqlite3_reset(stmt);
1037
                            sqlite3_reset(stmt);
991
                            sqlite3_bind_int(stmt, 1, i);
1038
                            sqlite3_bind_int(stmt, 1, i);
992
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 0));
1039
                            sqlite3_bind_double(stmt, sdf_idx, sqlite3_column_double(stmt2, 0));
993
                            sqlite3_bind_double(stmt, vec_idx, sqlite3_column_double(stmt3, 0));
1040
                            sqlite3_bind_double(stmt, vec_idx, sqlite3_column_double(stmt3, 0));
994
                            sqlite3_step(stmt);
1041
                            sqlite3_step(stmt);
995
                        }
1042
                        }
996
                        sqlite3_reset(stmt3);
1043
                        sqlite3_reset(stmt3);
997
                    }
1044
                    }
998
                }
1045
                }
999
            }
1046
            }
1000
 
1047
 
1001
            sqlite3_finalize(stmt);
1048
            sqlite3_finalize(stmt);
1002
            sqlite3_finalize(stmt2);
1049
            sqlite3_finalize(stmt2);
1003
            sqlite3_finalize(stmt3);
1050
            sqlite3_finalize(stmt3);
1004
            _sqlite_commit;
1051
            _sqlite_commit;
1005
 
1052
 
1006
            UNUSE_SDF2(iname_op2);
1053
            UNUSE_SDF2(iname_op2);
1007
        }
1054
        }
1008
    } else if (functype == 1 && funcname[0] != '!') { /* unary not operator */
1055
    } else if (functype == 1 && funcname[0] != '!') { /* unary not operator */
1009
        iname = _create_svector1(R_NilValue, "bit", NULL, TRUE);
1056
        iname = _create_svector1(R_NilValue, "bit", NULL, TRUE);
1010
        sprintf(g_sql_buf[2], "insert into [%s].sdf_data "
1057
        sprintf(g_sql_buf[2], "insert into [%s].sdf_data "
1011
                    "select [row name], [%s] == 0 from [%s].sdf_data", 
1058
                    "select [row name], [%s] == 0 from [%s].sdf_data", 
1012
                    iname, varname_src, iname_src);
1059
                    iname, varname_src, iname_src);
1013
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
1060
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
1014
        _sqlite_error(res);
1061
        _sqlite_error(res);
1015
        sqlite3_step(stmt);
1062
        sqlite3_step(stmt);
1016
        sqlite3_finalize(stmt);
1063
        sqlite3_finalize(stmt);
1017
    }
1064
    }
1018
 
1065
 
1019
    if (iname != NULL) {
1066
    if (iname != NULL) {
1020
        return _create_svector_sexp(iname, "sdf_data", "V1", 
1067
        return _create_svector_sexp(iname, "sdf_data", "V1", 
1021
                (functype == 0) ? "numeric" : "logical");
1068
                (functype == 0) ? "numeric" : "logical");
1022
        UNUSE_SDF2(iname);
1069
        UNUSE_SDF2(iname);
1023
    }
1070
    }
1024
 
1071
 
1025
    UNUSE_SDF2(iname_src);
1072
    UNUSE_SDF2(iname_src);
1026
 
1073
 
1027
    return R_NilValue;
1074
    return R_NilValue;
1028
 
1075
 
1029
}
1076
}
1030
 
1077
 
1031
SEXP sdf_do_variable_summary(SEXP func, SEXP vector, SEXP na_rm) {
1078
SEXP sdf_do_variable_summary(SEXP func, SEXP vector, SEXP na_rm) {
1032
    char *iname_src, *varname_src, *funcname;
1079
    char *iname_src, *varname_src, *funcname;
1033
    int res;
1080
    int res;
1034
    sqlite3_stmt *stmt;
1081
    sqlite3_stmt *stmt;
1035
    double _ret = NA_REAL, _ret2; SEXP ret;
1082
    double _ret = NA_REAL, _ret2; SEXP ret;
1036
 
1083
 
1037
    /* get data from arguments (function name and sqlite.vector stuffs) */
1084
    /* get data from arguments (function name and sqlite.vector stuffs) */
1038
    funcname = CHAR_ELT(func, 0);
1085
    funcname = CHAR_ELT(func, 0);
1039
    iname_src = SDF_INAME(vector);
1086
    iname_src = SDF_INAME(vector);
1040
    varname_src = SVEC_VARNAME(vector);
1087
    varname_src = SVEC_VARNAME(vector);
1041
 
1088
 
1042
    if (!USE_SDF1(iname_src, TRUE, FALSE)) return R_NilValue;
1089
    if (!USE_SDF1(iname_src, TRUE, FALSE)) return R_NilValue;
1043
 
1090
 
1044
    g_narm = LOGICAL(na_rm)[0];
1091
    g_narm = LOGICAL(na_rm)[0];
1045
    if (strcmp(funcname, "range") == 0) {
1092
    if (strcmp(funcname, "range") == 0) {
1046
        /* special handling for range. use min then max */
1093
        /* special handling for range. use min then max */
1047
        _init_sqlite_function_accumulator();
1094
        _init_sqlite_function_accumulator();
1048
        sprintf(g_sql_buf[0], "select min_df([%s]) from [%s].sdf_data", varname_src, iname_src);
1095
        sprintf(g_sql_buf[0], "select min_df([%s]) from [%s].sdf_data", varname_src, iname_src);
1049
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1096
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1050
        if (_sqlite_error(res)) return R_NilValue;
1097
        if (_sqlite_error(res)) return R_NilValue;
1051
        sqlite3_step(stmt); 
1098
        sqlite3_step(stmt); 
1052
        _ret = sqlite3_column_double(stmt, 0);
1099
        _ret = sqlite3_column_double(stmt, 0);
1053
        sqlite3_finalize(stmt);
1100
        sqlite3_finalize(stmt);
1054
 
1101
 
1055
        if (R_IsNA(_ret) && !g_narm) {
1102
        if (R_IsNA(_ret) && !g_narm) {
1056
            PROTECT(ret = NEW_NUMERIC(2));
1103
            PROTECT(ret = NEW_NUMERIC(2));
1057
            REAL(ret)[0] = REAL(ret)[1] = R_NaReal;
1104
            REAL(ret)[0] = REAL(ret)[1] = R_NaReal;
1058
            goto __sdf_do_variable_summary_out;
1105
            goto __sdf_do_variable_summary_out;
1059
        }
1106
        }
1060
        
1107
        
1061
        _init_sqlite_function_accumulator();
1108
        _init_sqlite_function_accumulator();
1062
        sprintf(g_sql_buf[0], "select max_df([%s]) from [%s].sdf_data", varname_src, iname_src);
1109
        sprintf(g_sql_buf[0], "select max_df([%s]) from [%s].sdf_data", varname_src, iname_src);
1063
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1110
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1064
        if (_sqlite_error(res)) return R_NilValue;
1111
        if (_sqlite_error(res)) return R_NilValue;
1065
        sqlite3_step(stmt); 
1112
        sqlite3_step(stmt); 
1066
        _ret2 = sqlite3_column_double(stmt, 0);
1113
        _ret2 = sqlite3_column_double(stmt, 0);
1067
        sqlite3_finalize(stmt);
1114
        sqlite3_finalize(stmt);
1068
 
1115
 
1069
        /* if there is NA, then the if above should have caught it already */
1116
        /* if there is NA, then the if above should have caught it already */
1070
        PROTECT(ret = NEW_NUMERIC(2));
1117
        PROTECT(ret = NEW_NUMERIC(2));
1071
        REAL(ret)[0] = _ret;
1118
        REAL(ret)[0] = _ret;
1072
        REAL(ret)[1] = _ret2;
1119
        REAL(ret)[1] = _ret2;
1073
    } else {
1120
    } else {
1074
        _init_sqlite_function_accumulator();
1121
        _init_sqlite_function_accumulator();
1075
        sprintf(g_sql_buf[0], "select %s_df([%s]) from [%s].sdf_data", funcname, varname_src, iname_src);
1122
        sprintf(g_sql_buf[0], "select %s_df([%s]) from [%s].sdf_data", funcname, varname_src, iname_src);
1076
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1123
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1077
        if (_sqlite_error(res)) return R_NilValue;
1124
        if (_sqlite_error(res)) return R_NilValue;
1078
        res = sqlite3_step(stmt); 
1125
        res = sqlite3_step(stmt); 
1079
        _ret = sqlite3_column_double(stmt, 0);
1126
        _ret = sqlite3_column_double(stmt, 0);
1080
        sqlite3_finalize(stmt);
1127
        sqlite3_finalize(stmt);
1081
 
1128
 
1082
        if (strcmp(funcname, "all") == 0 || strcmp(funcname, "any") == 0) {
1129
        if (strcmp(funcname, "all") == 0 || strcmp(funcname, "any") == 0) {
1083
            PROTECT(ret = NEW_LOGICAL(1));
1130
            PROTECT(ret = NEW_LOGICAL(1));
1084
            if (R_IsNA(_ret)) LOGICAL(ret)[0] = NA_INTEGER;
1131
            if (R_IsNA(_ret)) LOGICAL(ret)[0] = NA_INTEGER;
1085
            else LOGICAL(ret)[0] = (_ret != 0);
1132
            else LOGICAL(ret)[0] = (_ret != 0);
1086
        } else {
1133
        } else {
1087
            PROTECT(ret = NEW_NUMERIC(1));
1134
            PROTECT(ret = NEW_NUMERIC(1));
1088
            REAL(ret)[0] = _ret;
1135
            REAL(ret)[0] = _ret;
1089
        }
1136
        }
1090
    }
1137
    }
1091
 
1138
 
1092
__sdf_do_variable_summary_out:
1139
__sdf_do_variable_summary_out:
1093
    UNPROTECT(1);
1140
    UNPROTECT(1);
1094
    return ret;
1141
    return ret;
1095
}
1142
}
1096
 
1143
 
1097
 
1144
 
1098
SEXP sdf_sort_variable(SEXP svec, SEXP decreasing) {
1145
SEXP sdf_sort_variable(SEXP svec, SEXP decreasing) {
1099
    char *iname, *tblname, *varname, *type, *sort_type, *iname2;
1146
    char *iname, *tblname, *varname, *type, *sort_type;
1100
    sqlite3_stmt *stmt;
1147
    sqlite3_stmt *stmt;
1101
    int res;
1148
    int res;
1102
 
1149
 
1103
    iname = SDF_INAME(svec);
1150
    iname = SDF_INAME(svec);
1104
    tblname = SVEC_TBLNAME(svec);
1151
    tblname = SVEC_TBLNAME(svec);
1105
    varname = SVEC_VARNAME(svec);
1152
    varname = SVEC_VARNAME(svec);
1106
 
1153
 
1107
    if (!USE_SDF1(iname, TRUE, TRUE)) return R_NilValue;
1154
    if (!USE_SDF1(iname, TRUE, TRUE)) return R_NilValue;
1108
 
1155
 
1109
    /* determine type of svec */
1156
    /* determine type of svec */
1110
    sprintf(g_sql_buf[0], "select [%s] from [%s].[%s] limit 1", varname, iname, tblname);
1157
    sprintf(g_sql_buf[0], "select [%s] from [%s].[%s] limit 1", varname, iname, tblname);
1111
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
1158
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
1112
    _sqlite_error(res);
1159
    _sqlite_error(res);
1113
    sqlite3_step(stmt);
1160
    sqlite3_step(stmt);
1114
    strcpy(g_sql_buf[0], sqlite3_column_decltype(stmt, 0));
1161
    strcpy(g_sql_buf[0], sqlite3_column_decltype(stmt, 0));
1115
    sqlite3_finalize(stmt);
1162
    sqlite3_finalize(stmt);
1116
 
1163
 
1117
    if (TEST_SDFVECTORTYPE(svec, "factor")) { /* copy factor table to iname */
1164
    if (TEST_SDFVECTORTYPE(svec, "factor")) { /* copy factor table to iname */
1118
        if (TEST_SDFVECTORTYPE(svec, "ordered")) type = "ordered";
1165
        if (TEST_SDFVECTORTYPE(svec, "ordered")) type = "ordered";
1119
        else type = "factor";
1166
        else type = "factor";
1120
        _copy_factor_levels2(type, iname, varname, iname, "V1");
1167
        _copy_factor_levels2(type, iname, varname, iname, "V1");
1121
    } else type = CHAR_ELT(GET_SDFVECTORTYPE(svec), 0);
1168
    } else type = CHAR_ELT(GET_SDFVECTORTYPE(svec), 0);
1122
 
1169
 
1123
    if (strcmp(tblname, "sdf_data") == 0) {
1170
    if (strcmp(tblname, "sdf_data") == 0) {
1124
        /* cache sorted data if column to be sorted comes from main sdf_data */
1171
        /* cache sorted data if column to be sorted comes from main sdf_data */
1125
 
1172
 
1126
        /* test if there is already a sort_varname table */
1173
        /* test if there is already a sort_varname table */
1127
        sort_type = (LOGICAL(decreasing)[0]) ? "desc" : "asc";
1174
        sort_type = (LOGICAL(decreasing)[0]) ? "desc" : "asc";
1128
        sprintf(g_sql_buf[1], "select count(*) from [%s].sqlite_master "
1175
        sprintf(g_sql_buf[1], "select count(*) from [%s].sqlite_master "
1129
                "where type='table' and name='sort_%s_%s'", iname, sort_type, varname);
1176
                "where type='table' and name='sort_%s_%s'", iname, sort_type, varname);
1130
        sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
1177
        sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
1131
        sqlite3_step(stmt);
1178
        sqlite3_step(stmt);
1132
        res = sqlite3_column_int(stmt, 0);
1179
        res = sqlite3_column_int(stmt, 0);
1133
        sqlite3_finalize(stmt);
1180
        sqlite3_finalize(stmt);
1134
 
1181
 
1135
        if (res == 0) {
1182
        if (res == 0) {
1136
            sprintf(g_sql_buf[1], "create table [%s].[sort_%s_%s] ([%s] %s)", 
1183
            sprintf(g_sql_buf[1], "create table [%s].[sort_%s_%s] ([%s] %s)", 
1137
                    iname, sort_type, varname, varname, g_sql_buf[0]);
1184
                    iname, sort_type, varname, varname, g_sql_buf[0]);
1138
            if (_sqlite_error(_sqlite_exec(g_sql_buf[1]))) 
1185
            if (_sqlite_error(_sqlite_exec(g_sql_buf[1]))) 
1139
                    error("Can't create table: %s", g_sql_buf[1]);
1186
                    error("Can't create table: %s", g_sql_buf[1]);
1140
 
1187
 
1141
            /* insert to new sdf ordered */
1188
            /* insert to new sdf ordered */
1142
            sprintf(g_sql_buf[0], "insert into [%s].[sort_%s_%s] "
1189
            sprintf(g_sql_buf[0], "insert into [%s].[sort_%s_%s] "
1143
                    "select [%s] from [%s].[%s] order by [%s] %s", 
1190
                    "select [%s] from [%s].[%s] order by [%s] %s", 
1144
                    iname, sort_type, varname, varname, iname, tblname, varname, sort_type);
1191
                    iname, sort_type, varname, varname, iname, tblname, varname, sort_type);
1145
                    
1192
                    
1146
            res = _sqlite_exec(g_sql_buf[0]);
1193
            res = _sqlite_exec(g_sql_buf[0]);
1147
            if (_sqlite_error(res)) error("Can't insert: %s", g_sql_buf[0]);
1194
            if (_sqlite_error(res)) error("Can't insert: %s", g_sql_buf[0]);
1148
        }
1195
        }
1149
 
1196
 
1150
        UNUSE_SDF2(iname);
1197
        UNUSE_SDF2(iname);
1151
        sprintf(g_sql_buf[0], "sort_%s_%s", sort_type, varname);
1198
        sprintf(g_sql_buf[0], "sort_%s_%s", sort_type, varname);
1152
        return _create_svector_sexp(iname, g_sql_buf[0], varname, type);
1199
        return _create_svector_sexp(iname, g_sql_buf[0], varname, type);
1153
    } else {
1200
    } else {
1154
        /* create a new sdf table, copy data to that */
1201
        /* create a new sdf table, copy data to that */
1155
 
1202
 
1156
        /* create a sorted column */
1203
        /* create a sorted column */
1157
 
1204
 
1158
        error("Not yet supported.");
1205
        error("Not yet supported.");
1159
    }
1206
    }
1160
 
1207
 
1161
    return R_NilValue;
1208
    return R_NilValue;
1162
}
1209
}
1163
 
1210
 
1164
/****************************************************************************
1211
/****************************************************************************
1165
 * VECTOR MATH/OPS/GROUP OPERATIONS
1212
 * VECTOR MATH/OPS/GROUP OPERATIONS
1166
 ****************************************************************************/
1213
 ****************************************************************************/
1167
struct accumulator_t {
1214
struct accumulator_t {
1168
    /* long double acts weird here, but if it's not long double,
1215
    /* long double acts weird here, but if it's not long double,
1169
     * it f*cks up sum() */
1216
     * it f*cks up sum() */
1170
    long double accumulator;
1217
    long double accumulator;
1171
    int started;
1218
    int started;
1172
};
1219
};
1173
 
1220
 
1174
R_INLINE int __vecmath_checkarg(sqlite3_context *ctx, sqlite3_value *arg, double *value) {
1221
R_INLINE int __vecmath_checkarg(sqlite3_context *ctx, sqlite3_value *arg, double *value) {
1175
    int ret = 1;
1222
    int ret = 1;
1176
    if (sqlite3_value_type(arg) == SQLITE_NULL) { 
1223
    if (sqlite3_value_type(arg) == SQLITE_NULL) { 
1177
        sqlite3_result_null(ctx); 
1224
        sqlite3_result_null(ctx); 
1178
        ret = 0;
1225
        ret = 0;
1179
    } else {
1226
    } else {
1180
        if (sqlite3_value_type(arg) == SQLITE_INTEGER) 
1227
        if (sqlite3_value_type(arg) == SQLITE_INTEGER) 
1181
            *value = sqlite3_value_int(arg); 
1228
            *value = sqlite3_value_int(arg); 
1182
        else *value = sqlite3_value_double(arg); 
1229
        else *value = sqlite3_value_double(arg); 
1183
    }
1230
    }
1184
    return ret;
1231
    return ret;
1185
}
1232
}
1186
 
1233
 
1187
#define SQLITE_MATH_FUNC1(name, func) static void __vecmath_ ## name(\
1234
#define SQLITE_MATH_FUNC1(name, func) static void __vecmath_ ## name(\
1188
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1235
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1189
    double value; \
1236
    double value; \
1190
    if (__vecmath_checkarg(ctx, argv[0], &value)) { \
1237
    if (__vecmath_checkarg(ctx, argv[0], &value)) { \
1191
        sqlite3_result_double(ctx, func(value)); \
1238
        sqlite3_result_double(ctx, func(value)); \
1192
    }  \
1239
    }  \
1193
}
1240
}
1194
 
1241
 
1195
#define SQLITE_MATH_FUNC2(name, func) static void __vecmath_ ## name(\
1242
#define SQLITE_MATH_FUNC2(name, func) static void __vecmath_ ## name(\
1196
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1243
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1197
    double value1, value2; \
1244
    double value1, value2; \
1198
    if (__vecmath_checkarg(ctx, argv[0], &value1) && \
1245
    if (__vecmath_checkarg(ctx, argv[0], &value1) && \
1199
        __vecmath_checkarg(ctx, argv[1], &value2)) { \
1246
        __vecmath_checkarg(ctx, argv[1], &value2)) { \
1200
        sqlite3_result_double(ctx, func((long double)value1, (long double)value2)); \
1247
        sqlite3_result_double(ctx, func((long double)value1, (long double)value2)); \
1201
    }  \
1248
    }  \
1202
}
1249
}
1203
 
1250
 
1204
#define SQLITE_MATH_FUNC_CUM(name, func) static void __vecmath_ ## name(\
1251
#define SQLITE_MATH_FUNC_CUM(name, func) static void __vecmath_ ## name(\
1205
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1252
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1206
    double value; \
1253
    double value; \
1207
    if (__vecmath_checkarg(ctx, argv[0], &value)) { \
1254
    if (__vecmath_checkarg(ctx, argv[0], &value)) { \
1208
        if (g_start) { g_start = 0; g_accumulator = value; } \
1255
        if (g_start) { g_start = 0; g_accumulator = value; } \
1209
        else g_accumulator = func(g_accumulator, value); \
1256
        else g_accumulator = func(g_accumulator, value); \
1210
        sqlite3_result_double(ctx, g_accumulator); \
1257
        sqlite3_result_double(ctx, g_accumulator); \
1211
    }  \
1258
    }  \
1212
}
1259
}
1213
 
1260
 
1214
#define LOGBASE(a, b) log(a)/log(b)
1261
#define LOGBASE(a, b) log(a)/log(b)
1215
 
1262
 
1216
/* SQLITE_MATH_FUNC1(abs, abs)   in SQLite */
1263
/* SQLITE_MATH_FUNC1(abs, abs)   in SQLite */
1217
SQLITE_MATH_FUNC1(sign, sign)   /* in R */
1264
SQLITE_MATH_FUNC1(sign, sign)   /* in R */
1218
SQLITE_MATH_FUNC1(sqrt, sqrt)
1265
SQLITE_MATH_FUNC1(sqrt, sqrt)
1219
SQLITE_MATH_FUNC1(floor, floor)
1266
SQLITE_MATH_FUNC1(floor, floor)
1220
SQLITE_MATH_FUNC1(ceiling, ceil)
1267
SQLITE_MATH_FUNC1(ceiling, ceil)
1221
SQLITE_MATH_FUNC1(trunc, ftrunc) /* in R */
1268
SQLITE_MATH_FUNC1(trunc, ftrunc) /* in R */
1222
/*SQLITE_MATH_FUNC2(round, fprec)  2 arg, in SQLite, but override with R's version */
1269
/*SQLITE_MATH_FUNC2(round, fprec)  2 arg, in SQLite, but override with R's version */
1223
SQLITE_MATH_FUNC2(signif, fround) /* 2 arg, in R */
1270
SQLITE_MATH_FUNC2(signif, fround) /* 2 arg, in R */
1224
SQLITE_MATH_FUNC1(exp, exp)
1271
SQLITE_MATH_FUNC1(exp, exp)
1225
SQLITE_MATH_FUNC2(log, LOGBASE) /* 2 arg */
1272
SQLITE_MATH_FUNC2(log, LOGBASE) /* 2 arg */
1226
SQLITE_MATH_FUNC1(cos, cos)
1273
SQLITE_MATH_FUNC1(cos, cos)
1227
SQLITE_MATH_FUNC1(sin, sin)
1274
SQLITE_MATH_FUNC1(sin, sin)
1228
SQLITE_MATH_FUNC1(tan, tan)
1275
SQLITE_MATH_FUNC1(tan, tan)
1229
SQLITE_MATH_FUNC1(acos, acos)
1276
SQLITE_MATH_FUNC1(acos, acos)
1230
SQLITE_MATH_FUNC1(asin, asin)
1277
SQLITE_MATH_FUNC1(asin, asin)
1231
SQLITE_MATH_FUNC1(atan, atan)
1278
SQLITE_MATH_FUNC1(atan, atan)
1232
SQLITE_MATH_FUNC1(cosh, cosh)
1279
SQLITE_MATH_FUNC1(cosh, cosh)
1233
SQLITE_MATH_FUNC1(sinh, sinh)
1280
SQLITE_MATH_FUNC1(sinh, sinh)
1234
SQLITE_MATH_FUNC1(tanh, tanh)
1281
SQLITE_MATH_FUNC1(tanh, tanh)
1235
SQLITE_MATH_FUNC1(acosh, acosh)  /* nowhere in include?? */
1282
SQLITE_MATH_FUNC1(acosh, acosh)  /* nowhere in include?? */
1236
SQLITE_MATH_FUNC1(asinh, asinh)  /* nowhere in include?? */
1283
SQLITE_MATH_FUNC1(asinh, asinh)  /* nowhere in include?? */
1237
SQLITE_MATH_FUNC1(atanh, atanh)  /* nowhere in include?? */
1284
SQLITE_MATH_FUNC1(atanh, atanh)  /* nowhere in include?? */
1238
SQLITE_MATH_FUNC1(lgamma, lgammafn) /* in R */
1285
SQLITE_MATH_FUNC1(lgamma, lgammafn) /* in R */
1239
SQLITE_MATH_FUNC1(gamma, gammafn) /* in R */
1286
SQLITE_MATH_FUNC1(gamma, gammafn) /* in R */
1240
/* SQLITE_MATH_FUNC1(gammaCody, gammaCody)   * in R ?? */
1287
/* SQLITE_MATH_FUNC1(gammaCody, gammaCody)   * in R ?? */
1241
SQLITE_MATH_FUNC1(digamma, digamma) /* in R */    
1288
SQLITE_MATH_FUNC1(digamma, digamma) /* in R */    
1242
SQLITE_MATH_FUNC1(trigamma, trigamma) /* in R */
1289
SQLITE_MATH_FUNC1(trigamma, trigamma) /* in R */
1243
 
1290
 
1244
#define SUM(a, b)  ((long double)(a) + (b))
1291
#define SUM(a, b)  ((long double)(a) + (b))
1245
#define PROD(a, b) (a) * (b)
1292
#define PROD(a, b) (a) * (b)
1246
#define MIN(a, b) ((a) <= (b)) ? (a) : (b)
1293
#define MIN(a, b) ((a) <= (b)) ? (a) : (b)
1247
#define MAX(a, b) ((a) >= (b)) ? (a) : (b)
1294
#define MAX(a, b) ((a) >= (b)) ? (a) : (b)
1248
#define ALL(a, b) (((a) == 0) || ((b) == 0)) ? 0 : 1
1295
#define ALL(a, b) (((a) == 0) || ((b) == 0)) ? 0 : 1
1249
#define ANY(a, b) (((a) == 0) && ((b) == 0)) ? 0 : 1
1296
#define ANY(a, b) (((a) == 0) && ((b) == 0)) ? 0 : 1
1250
 
1297
 
1251
SQLITE_MATH_FUNC_CUM(cumsum, SUM)
1298
SQLITE_MATH_FUNC_CUM(cumsum, SUM)
1252
SQLITE_MATH_FUNC_CUM(cumprod, PROD)
1299
SQLITE_MATH_FUNC_CUM(cumprod, PROD)
1253
SQLITE_MATH_FUNC_CUM(cummin, MIN)
1300
SQLITE_MATH_FUNC_CUM(cummin, MIN)
1254
SQLITE_MATH_FUNC_CUM(cummax, MAX)
1301
SQLITE_MATH_FUNC_CUM(cummax, MAX)
1255
 
1302
 
1256
#define SQLITE_SUMMARY_FUNC(name, func) static void __vecsummary_ ## name(\
1303
#define SQLITE_SUMMARY_FUNC(name, func) static void __vecsummary_ ## name(\
1257
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1304
        sqlite3_context *ctx, int argc, sqlite3_value **argv) { \
1258
    double value; \
1305
    double value; \
1259
    struct accumulator_t *acc; \
1306
    struct accumulator_t *acc; \
1260
    acc = sqlite3_aggregate_context(ctx, sizeof(struct accumulator_t)); \
1307
    acc = sqlite3_aggregate_context(ctx, sizeof(struct accumulator_t)); \
1261
    if (!g_narm && R_IsNA(acc->accumulator)) return; /* NA if na.rm=F & NA found */ \
1308
    if (!g_narm && R_IsNA(acc->accumulator)) return; /* NA if na.rm=F & NA found */ \
1262
    if (sqlite3_value_type(argv[0]) != SQLITE_NULL) {  \
1309
    if (sqlite3_value_type(argv[0]) != SQLITE_NULL) {  \
1263
        if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER) {  \
1310
        if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER) {  \
1264
            int tmp = sqlite3_value_int(argv[0]); \
1311
            int tmp = sqlite3_value_int(argv[0]); \
1265
            value = (tmp == NA_INTEGER) ? R_NaReal : tmp; \
1312
            value = (tmp == NA_INTEGER) ? R_NaReal : tmp; \
1266
        } else value = sqlite3_value_double(argv[0]);  \
1313
        } else value = sqlite3_value_double(argv[0]);  \
1267
        if (R_IsNA(value)) { \
1314
        if (R_IsNA(value)) { \
1268
            if (!g_narm) acc->accumulator = value; return; /* else ignore */ \
1315
            if (!g_narm) acc->accumulator = value; return; /* else ignore */ \
1269
        } else if (!acc->started) { \
1316
        } else if (!acc->started) { \
1270
            acc->started = 1; \
1317
            acc->started = 1; \
1271
            acc->accumulator = value; \
1318
            acc->accumulator = value; \
1272
        } else acc->accumulator = func(acc->accumulator, value); \
1319
        } else acc->accumulator = func(acc->accumulator, value); \
1273
    } \
1320
    } \
1274
}
1321
}
1275
 
1322
 
1276
SQLITE_SUMMARY_FUNC(all_df, ALL)
1323
SQLITE_SUMMARY_FUNC(all_df, ALL)
1277
SQLITE_SUMMARY_FUNC(any_df, ANY)
1324
SQLITE_SUMMARY_FUNC(any_df, ANY)
1278
SQLITE_SUMMARY_FUNC(sum_df, SUM)
1325
SQLITE_SUMMARY_FUNC(sum_df, SUM)
1279
SQLITE_SUMMARY_FUNC(prod_df, PROD)
1326
SQLITE_SUMMARY_FUNC(prod_df, PROD)
1280
SQLITE_SUMMARY_FUNC(min_df, MIN)
1327
SQLITE_SUMMARY_FUNC(min_df, MIN)
1281
SQLITE_SUMMARY_FUNC(max_df, MAX)
1328
SQLITE_SUMMARY_FUNC(max_df, MAX)
1282
 
1329
 
1283
static void __vecsummary_finalize(sqlite3_context *ctx) {
1330
static void __vecsummary_finalize(sqlite3_context *ctx) {
1284
    /* g_accumulator already summarizes it. just return that */
1331
    /* g_accumulator already summarizes it. just return that */
1285
    struct accumulator_t *acc = (struct accumulator_t *)
1332
    struct accumulator_t *acc = (struct accumulator_t *)
1286
                sqlite3_aggregate_context(ctx, sizeof(struct accumulator_t)); 
1333
                sqlite3_aggregate_context(ctx, sizeof(struct accumulator_t)); 
1287
    sqlite3_result_double(ctx, acc->accumulator);
1334
    sqlite3_result_double(ctx, acc->accumulator);
1288
}
1335
}
1289
 
1336
 
1290
static void __r_modulo(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
1337
static void __r_modulo(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
1291
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL ||
1338
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL ||
1292
        sqlite3_value_type(argv[1]) == SQLITE_NULL) { 
1339
        sqlite3_value_type(argv[1]) == SQLITE_NULL) { 
1293
        sqlite3_result_null(ctx); 
1340
        sqlite3_result_null(ctx); 
1294
    } else {
1341
    } else {
1295
        double v1, v2, q, tmp;
1342
        double v1, v2, q, tmp;
1296
        if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER && 
1343
        if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER && 
1297
            sqlite3_value_type(argv[1]) == SQLITE_INTEGER) {
1344
            sqlite3_value_type(argv[1]) == SQLITE_INTEGER) {
1298
            int i1, i2;
1345
            int i1, i2;
1299
            i1 = sqlite3_value_int(argv[0]);
1346
            i1 = sqlite3_value_int(argv[0]);
1300
            i2 = sqlite3_value_int(argv[1]);
1347
            i2 = sqlite3_value_int(argv[1]);
1301
            if (i1 > 0 && i2 > 0) { 
1348
            if (i1 > 0 && i2 > 0) { 
1302
                sqlite3_result_int(ctx, i1 % i2); return;
1349
                sqlite3_result_int(ctx, i1 % i2); return;
1303
            }
1350
            }
1304
            v1 = i1; v2 = i2;
1351
            v1 = i1; v2 = i2;
1305
        } else {
1352
        } else {
1306
            v1 = sqlite3_value_double(argv[0]);
1353
            v1 = sqlite3_value_double(argv[0]);
1307
            v2 = sqlite3_value_double(argv[1]);
1354
            v2 = sqlite3_value_double(argv[1]);
1308
        }
1355
        }
1309
        /* copied from myfmod() in src/main/arithmetic.c */
1356
        /* copied from myfmod() in src/main/arithmetic.c */
1310
        q = v1 / v2; 
1357
        q = v1 / v2; 
1311
        if (v2 == 0) sqlite3_result_double(ctx, R_NaN);
1358
        if (v2 == 0) sqlite3_result_double(ctx, R_NaN);
1312
        tmp = v1 - floor(q) * v2;
1359
        tmp = v1 - floor(q) * v2;
1313
        /* checking omitted */
1360
        /* checking omitted */
1314
        q = floor(tmp/v2);
1361
        q = floor(tmp/v2);
1315
        sqlite3_result_double(ctx, tmp - q*v2);
1362
        sqlite3_result_double(ctx, tmp - q*v2);
1316
 
1363
 
1317
    }
1364
    }
1318
}
1365
}
1319
 
1366
 
1320
static void __r_intdiv(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
1367
static void __r_intdiv(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
1321
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL ||
1368
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL ||
1322
        sqlite3_value_type(argv[1]) == SQLITE_NULL) { 
1369
        sqlite3_value_type(argv[1]) == SQLITE_NULL) { 
1323
        sqlite3_result_null(ctx); 
1370
        sqlite3_result_null(ctx); 
1324
    } else {
1371
    } else {
1325
        double v1, v2;
1372
        double v1, v2;
1326
        if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER && 
1373
        if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER && 
1327
            sqlite3_value_type(argv[1]) == SQLITE_INTEGER) {
1374
            sqlite3_value_type(argv[1]) == SQLITE_INTEGER) {
1328
            int i1, i2;
1375
            int i1, i2;
1329
            i1 = sqlite3_value_int(argv[0]);
1376
            i1 = sqlite3_value_int(argv[0]);
1330
            i2 = sqlite3_value_int(argv[1]);
1377
            i2 = sqlite3_value_int(argv[1]);
1331
            if (i1 == NA_INTEGER || i2 == NA_INTEGER) {
1378
            if (i1 == NA_INTEGER || i2 == NA_INTEGER) {
1332
                sqlite3_result_int(ctx, NA_INTEGER); return;
1379
                sqlite3_result_int(ctx, NA_INTEGER); return;
1333
            } else if (i2 == 0) {
1380
            } else if (i2 == 0) {
1334
                sqlite3_result_int(ctx, 0); return;
1381
                sqlite3_result_int(ctx, 0); return;
1335
            }
1382
            }
1336
            v1 = i1; v2 = i2;
1383
            v1 = i1; v2 = i2;
1337
        } else {
1384
        } else {
1338
            v1 = sqlite3_value_double(argv[0]);
1385
            v1 = sqlite3_value_double(argv[0]);
1339
            v2 = sqlite3_value_double(argv[1]);
1386
            v2 = sqlite3_value_double(argv[1]);
1340
        }
1387
        }
1341
        /* copied from IDIVOP cases in src/main/arithmetic.c */
1388
        /* copied from IDIVOP cases in src/main/arithmetic.c */
1342
        sqlite3_result_double(ctx, floor(v1/v2));
1389
        sqlite3_result_double(ctx, floor(v1/v2));
1343
    }
1390
    }
1344
}
1391
}
1345
#define VMENTRY1(func)  {#func, __vecmath_ ## func}
1392
#define VMENTRY1(func)  {#func, __vecmath_ ## func}
1346
#define VSENTRY1(func)  {#func, __vecsummary_ ## func}
1393
#define VSENTRY1(func)  {#func, __vecsummary_ ## func}
1347
void __register_vector_math() {
1394
void __register_vector_math() {
1348
    int i, res;
1395
    int i, res;
1349
    static const struct {
1396
    static const struct {
1350
        char *name;
1397
        char *name;
1351
        void (*func)(sqlite3_context*, int, sqlite3_value**);
1398
        void (*func)(sqlite3_context*, int, sqlite3_value**);
1352
    } arr_func1[] = {
1399
    } arr_func1[] = {
1353
        VMENTRY1(sign),
1400
        VMENTRY1(sign),
1354
        VMENTRY1(sqrt),
1401
        VMENTRY1(sqrt),
1355
        VMENTRY1(floor),
1402
        VMENTRY1(floor),
1356
        VMENTRY1(ceiling),
1403
        VMENTRY1(ceiling),
1357
        VMENTRY1(trunc),
1404
        VMENTRY1(trunc),
1358
        VMENTRY1(exp),
1405
        VMENTRY1(exp),
1359
        VMENTRY1(cos),
1406
        VMENTRY1(cos),
1360
        VMENTRY1(sin),
1407
        VMENTRY1(sin),
1361
        VMENTRY1(tan),
1408
        VMENTRY1(tan),
1362
        VMENTRY1(acos),
1409
        VMENTRY1(acos),
1363
        VMENTRY1(asin),
1410
        VMENTRY1(asin),
1364
        VMENTRY1(atan),
1411
        VMENTRY1(atan),
1365
        VMENTRY1(cosh),
1412
        VMENTRY1(cosh),
1366
        VMENTRY1(sinh),
1413
        VMENTRY1(sinh),
1367
        VMENTRY1(tanh),
1414
        VMENTRY1(tanh),
1368
        VMENTRY1(acosh),
1415
        VMENTRY1(acosh),
1369
        VMENTRY1(asinh),
1416
        VMENTRY1(asinh),
1370
        VMENTRY1(atanh),
1417
        VMENTRY1(atanh),
1371
        VMENTRY1(lgamma),
1418
        VMENTRY1(lgamma),
1372
        VMENTRY1(gamma),
1419
        VMENTRY1(gamma),
1373
        VMENTRY1(digamma),
1420
        VMENTRY1(digamma),
1374
        VMENTRY1(trigamma),
1421
        VMENTRY1(trigamma),
1375
        VMENTRY1(cumsum),
1422
        VMENTRY1(cumsum),
1376
        VMENTRY1(cumprod),
1423
        VMENTRY1(cumprod),
1377
        VMENTRY1(cummin),
1424
        VMENTRY1(cummin),
1378
        VMENTRY1(cummax)
1425
        VMENTRY1(cummax)
1379
    }, arr_func2[] =  {
1426
    }, arr_func2[] =  {
1380
        {"r_mod", __r_modulo},
1427
        {"r_mod", __r_modulo},
1381
        {"r_intdiv", __r_intdiv},
1428
        {"r_intdiv", __r_intdiv},
1382
        /*VMENTRY1(round),*/
1429
        /*VMENTRY1(round),*/
1383
        VMENTRY1(signif),
1430
        VMENTRY1(signif),
1384
        VMENTRY1(log)
1431
        VMENTRY1(log)
1385
    }, arr_sum1[] = {
1432
    }, arr_sum1[] = {
1386
        VSENTRY1(all_df),  /* can't override sum, min, max */
1433
        VSENTRY1(all_df),  /* can't override sum, min, max */
1387
        VSENTRY1(any_df),
1434
        VSENTRY1(any_df),
1388
        VSENTRY1(sum_df),
1435
        VSENTRY1(sum_df),
1389
        VSENTRY1(prod_df),
1436
        VSENTRY1(prod_df),
1390
        VSENTRY1(min_df),
1437
        VSENTRY1(min_df),
1391
        VSENTRY1(max_df)
1438
        VSENTRY1(max_df)
1392
    };
1439
    };
1393
 
1440
 
1394
    int len = sizeof(arr_func1) / sizeof(arr_func1[0]);
1441
    int len = sizeof(arr_func1) / sizeof(arr_func1[0]);
1395
 
1442
 
1396
    for (i = 0; i < len; i++) {
1443
    for (i = 0; i < len; i++) {
1397
        res = sqlite3_create_function(g_workspace, arr_func1[i].name, 1, 
1444
        res = sqlite3_create_function(g_workspace, arr_func1[i].name, 1, 
1398
                SQLITE_ANY, NULL, arr_func1[i].func, NULL, NULL);
1445
                SQLITE_ANY, NULL, arr_func1[i].func, NULL, NULL);
1399
        _sqlite_error(res);
1446
        _sqlite_error(res);
1400
    }
1447
    }
1401
 
1448
 
1402
    len = sizeof(arr_func2) / sizeof(arr_func2[0]);
1449
    len = sizeof(arr_func2) / sizeof(arr_func2[0]);
1403
    for (i = 0; i < len; i++) {
1450
    for (i = 0; i < len; i++) {
1404
        res = sqlite3_create_function(g_workspace, arr_func2[i].name, 2, 
1451
        res = sqlite3_create_function(g_workspace, arr_func2[i].name, 2, 
1405
                SQLITE_ANY, NULL, arr_func2[i].func, NULL, NULL);
1452
                SQLITE_ANY, NULL, arr_func2[i].func, NULL, NULL);
1406
        _sqlite_error(res);
1453
        _sqlite_error(res);
1407
    }
1454
    }
1408
 
1455
 
1409
    len = sizeof(arr_sum1) / sizeof(arr_sum1[0]);
1456
    len = sizeof(arr_sum1) / sizeof(arr_sum1[0]);
1410
    for (i = 0; i < len; i++) {
1457
    for (i = 0; i < len; i++) {
1411
        res = sqlite3_create_function(g_workspace, arr_sum1[i].name, 1, 
1458
        res = sqlite3_create_function(g_workspace, arr_sum1[i].name, 1, 
1412
                SQLITE_ANY, NULL, NULL, arr_sum1[i].func, __vecsummary_finalize);
1459
                SQLITE_ANY, NULL, NULL, arr_sum1[i].func, __vecsummary_finalize);
1413
        _sqlite_error(res);
1460
        _sqlite_error(res);
1414
    }
1461
    }
1415
}
1462
}