The R Project SVN R-packages

Rev

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

Rev 3457 Rev 3471
1
#include <stdio.h>
1
#include <stdio.h>
2
#include <string.h>
2
#include <string.h>
3
#include "sqlite_dataframe.h"
3
#include "sqlite_dataframe.h"
4
 
4
 
5
/****************************************************************************
5
/****************************************************************************
6
 * UTILITY FUNCTIONS
6
 * UTILITY FUNCTIONS
7
 ****************************************************************************/
7
 ****************************************************************************/
8
 
8
 
9
/* if user supplied a name, return that name. otherwise, use the 
9
/* if user supplied a name, return that name. otherwise, use the 
10
 * default "data" */
10
 * default "data" */
11
static int _check_sdf_name(SEXP name, char **rname, char **iname, int *file_idx) {
11
static int _check_sdf_name(SEXP name, char **rname, char **iname, int *file_idx) {
12
    int namelen = 0;
12
    int namelen = 0;
13
 
13
 
14
    /* check if arg name is supplied */
14
    /* check if arg name is supplied */
15
    if (name == R_NilValue) {
15
    if (name == R_NilValue) {
16
        *rname = "data";
16
        *rname = "data";
17
        namelen = 5;
17
        namelen = 5;
18
        *iname = (char*)R_alloc(13, sizeof(char)); /* data10000.db\0 */
18
        *iname = (char*)R_alloc(13, sizeof(char)); /* data10000.db\0 */
19
        *file_idx = 1;
19
        *file_idx = 1;
20
        sprintf(*iname, "%s%d.db", *rname, *file_idx);
20
        sprintf(*iname, "%s%d.db", *rname, *file_idx);
21
    } else if (IS_CHARACTER(name)) {
21
    } else if (IS_CHARACTER(name)) {
22
        *rname = CHAR_ELT(name,0);
22
        *rname = CHAR_ELT(name,0);
23
        if (!_is_r_sym(*rname)) { 
23
        if (!_is_r_sym(*rname)) { 
24
            Rprintf("Error: supplied name \"%s\"is not a valid R symbol.\n", 
24
            Rprintf("Error: supplied name \"%s\"is not a valid R symbol.\n", 
25
                    *rname); 
25
                    *rname); 
26
            return FALSE; 
26
            return FALSE; 
27
        }
27
        }
28
        namelen = strlen(*rname);
28
        namelen = strlen(*rname);
29
        *iname = (char*)R_alloc(namelen + 9, sizeof(char)); /* <name>10000.db\0 */
29
        *iname = (char*)R_alloc(namelen + 9, sizeof(char)); /* <name>10000.db\0 */
30
        sprintf(*iname, "%s.db", *rname);
30
        sprintf(*iname, "%s.db", *rname);
31
    } else {
31
    } else {
32
        Rprintf("Error: the supplied value for arg name is not a string.\n");
32
        Rprintf("Error: the supplied value for arg name is not a string.\n");
33
    }
33
    }
34
    return namelen;
34
    return namelen;
35
}
35
}
36
 
36
 
37
static int _find_free_filename(char *rname, char **iname, int *namelen, int *file_idx) {
37
static int _find_free_filename2(char *rname, char **iname, int *namelen, int *file_idx) {
-
 
38
    sqlite3_stmt *stmt;
-
 
39
    sqlite3_prepare(g_workspace, "select 1 from workspace where internal_name=?", -1,
-
 
40
            &stmt, NULL);
38
    do {
41
    do {
39
        if (!_file_exists(*iname)) break;
42
        if (!_file_exists(*iname)) {
-
 
43
            sqlite3_reset(stmt);
-
 
44
            sqlite3_bind_text(stmt, 1, *iname, -1, SQLITE_STATIC);
-
 
45
            if (sqlite3_step(stmt) != SQLITE_ROW) break;
-
 
46
        }
40
        *namelen = sprintf(*iname, "%s%d.db", rname, ++(*file_idx)) - 3;
47
        *namelen = sprintf(*iname, "%s%d.db", rname, ++(*file_idx)) - 3;
41
    } while (*file_idx < 10000);
48
    } while (*file_idx < 10000);
42
 
49
 
-
 
50
    sqlite3_finalize(stmt);
43
    return *file_idx;
51
    return *file_idx;
44
}
52
}
45
 
53
 
46
/* creates an sdf attribute table */
54
/* creates an sdf attribute table */
47
static int _create_sdf_attribute2(const char *iname) {
55
static int _create_sdf_attribute2(const char *iname) {
48
    sprintf(g_sql_buf[2], "create table [%s].sdf_attributes(attr text, "
56
    sprintf(g_sql_buf[2], "create table [%s].sdf_attributes(attr text, "
49
            "value text, primary key (attr))", iname);
57
            "value text, primary key (attr))", iname);
50
    int res;
58
    int res;
51
    res = _sqlite_exec(g_sql_buf[2]);
59
    res = _sqlite_exec(g_sql_buf[2]);
52
    if (res == SQLITE_OK) {
60
    if (res == SQLITE_OK) {
53
        sprintf(g_sql_buf[2], "insert into [%s].sdf_attributes values ('name',"
61
        sprintf(g_sql_buf[2], "insert into [%s].sdf_attributes values ('name',"
54
                "'%s');", iname, iname);
62
                "'%s');", iname, iname);
55
        res = _sqlite_exec(g_sql_buf[2]);
63
        res = _sqlite_exec(g_sql_buf[2]);
56
    }
64
    }
57
    return res;
65
    return res;
58
}
66
}
59
 
67
 
60
char *_create_sdf_skeleton1(SEXP name, int *onamelen, int protect) {
68
char *_create_sdf_skeleton1(SEXP name, int *onamelen, int protect) {
61
    char *iname, *rname;
69
    char *iname, *rname;
62
    int namelen, file_idx = 0, res;
70
    int namelen, file_idx = 0, res;
63
 
71
 
64
    namelen = _check_sdf_name(name, &rname, &iname, &file_idx);
72
    namelen = _check_sdf_name(name, &rname, &iname, &file_idx);
65
 
73
 
66
    if (!namelen) return NULL;
74
    if (!namelen) return NULL;
67
 
75
 
68
    _find_free_filename(rname, &iname, &namelen, &file_idx);
76
    _find_free_filename2(rname, &iname, &namelen, &file_idx);
69
 
77
 
70
    if (file_idx >= 10000) { 
78
    if (file_idx >= 10000) { 
71
        Rprintf("Error: cannot find free SDF name.\n");
79
        Rprintf("Error: cannot find free SDF name.\n");
72
        return NULL;
80
        return NULL;
73
    }
81
    }
74
 
82
 
75
    /* add to workspace */
83
    /* add to workspace */
76
    strcpy(g_sql_buf[3], iname);
84
    strcpy(g_sql_buf[3], iname);
77
    iname[namelen] = 0; /* remove ".db" */
85
    iname[namelen] = 0; /* remove ".db" */
78
    res = _add_sdf1(g_sql_buf[3], iname);
86
    res = _add_sdf1(g_sql_buf[3], iname);
79
    if (_sqlite_error(res)) return NULL;
87
    if (_sqlite_error(res)) return NULL;
80
 
88
 
81
    /* detach SDF's if necessary to attach this one. if file does not
89
    /* detach SDF's if necessary to attach this one. if file does not
82
     * exist, then a sqlite db will be created after we make our 1st table */
90
     * exist, then a sqlite db will be created after we make our 1st table */
83
    if (!USE_SDF1(iname, FALSE, protect)) { /* _delete_sdf2(iname); */ return NULL; }
91
    if (!USE_SDF1(iname, FALSE, protect)) { /* _delete_sdf2(iname); */ return NULL; }
84
 
92
 
85
 
93
 
86
    /* create attributes table */
94
    /* create attributes table */
87
    res = _create_sdf_attribute2(iname);
95
    res = _create_sdf_attribute2(iname);
88
    if (_sqlite_error(res)) {
96
    if (_sqlite_error(res)) {
89
        sprintf(g_sql_buf[2], "detach '%s'", iname);
97
        sprintf(g_sql_buf[2], "detach '%s'", iname);
90
        _delete_sdf2(iname);
98
        _delete_sdf2(iname);
91
        return NULL; 
99
        return NULL; 
92
    }
100
    }
93
 
101
 
94
    if (onamelen) *onamelen = namelen;
102
    if (onamelen) *onamelen = namelen;
95
    return iname;
103
    return iname;
96
}
104
}
97
/* checks if a column has a corresponding factor|ordered table */
105
/* checks if a column has a corresponding factor|ordered table */
98
int _is_factor2(const char *iname, const char *factor_type, const char *colname) {
106
int _is_factor2(const char *iname, const char *factor_type, const char *colname) {
99
    sqlite3_stmt *stmt;
107
    sqlite3_stmt *stmt;
100
    sprintf(g_sql_buf[2], "select * from [%s].[%s %s]", iname, factor_type,
108
    sprintf(g_sql_buf[2], "select * from [%s].[%s %s]", iname, factor_type,
101
            colname);
109
            colname);
102
    int res;
110
    int res;
103
    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
111
    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
104
    sqlite3_finalize(stmt);
112
    sqlite3_finalize(stmt);
105
    return res == SQLITE_OK;
113
    return res == SQLITE_OK;
106
}
114
}
107
 
115
 
108
/* create a factor|ordered table */
116
/* create a factor|ordered table */
109
int _create_factor_table2(const char *iname, const char *factor_type, 
117
int _create_factor_table2(const char *iname, const char *factor_type, 
110
        const char *colname) {
118
        const char *colname) {
111
    sqlite3_stmt *stmt;
119
    sqlite3_stmt *stmt;
112
    sprintf(g_sql_buf[2], "create table [%s].[%s %s] (level int, label text, "
120
    sprintf(g_sql_buf[2], "create table [%s].[%s %s] (level int, label text, "
113
            "primary key(level), unique(label));", iname, factor_type, colname);
121
            "primary key(level), unique(label));", iname, factor_type, colname);
114
    int res;
122
    int res;
115
    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
123
    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
116
    if (res == SQLITE_OK) sqlite3_step(stmt);
124
    if (res == SQLITE_OK) sqlite3_step(stmt);
117
    sqlite3_finalize(stmt);
125
    sqlite3_finalize(stmt);
118
    return res; /* error on dup name? */
126
    return res; /* error on dup name? */
119
}
127
}
120
 
128
 
121
/* copy a factor|ordered table from a sdf(db) to another sdf(db) */
129
/* copy a factor|ordered table from a sdf(db) to another sdf(db) */
122
int _copy_factor_levels2(const char *factor_type, const char *iname_src,
130
int _copy_factor_levels2(const char *factor_type, const char *iname_src,
123
        const char *colname_src, const char *iname_dst, const char *colname_dst) {
131
        const char *colname_src, const char *iname_dst, const char *colname_dst) {
124
    sqlite3_stmt *stmt;
132
    sqlite3_stmt *stmt;
125
    int res;
133
    int res;
126
    res = _create_factor_table2(iname_dst, factor_type, colname_dst);
134
    res = _create_factor_table2(iname_dst, factor_type, colname_dst);
127
    if (res == SQLITE_OK) {
135
    if (res == SQLITE_OK) {
128
        sprintf(g_sql_buf[2], "insert into [%s].[%s %s] select * from [%s].[%s %s]",
136
        sprintf(g_sql_buf[2], "insert into [%s].[%s %s] select * from [%s].[%s %s]",
129
                iname_src, factor_type, colname_src, iname_dst, factor_type,
137
                iname_src, factor_type, colname_src, iname_dst, factor_type,
130
                colname_dst);
138
                colname_dst);
131
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
139
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
132
        if (res == SQLITE_OK) sqlite3_step(stmt);
140
        if (res == SQLITE_OK) sqlite3_step(stmt);
133
        sqlite3_finalize(stmt);
141
        sqlite3_finalize(stmt);
134
    }
142
    }
135
    return res; /* error on dup name? */
143
    return res; /* error on dup name? */
136
}
144
}
137
 
145
 
138
 
146
 
139
/* assumes stmt has col_cnt + 1 columns, col 0 is [row name]. returned SEXP is 
147
/* assumes stmt has col_cnt + 1 columns, col 0 is [row name]. returned SEXP is 
140
 * not UNPROTECT-ed, user will have to do that. will create the names &
148
 * not UNPROTECT-ed, user will have to do that. will create the names &
141
 * attach factor infos */
149
 * attach factor infos */
142
static SEXP _setup_df_sexp1(sqlite3_stmt *stmt, const char *iname, 
150
static SEXP _setup_df_sexp1(sqlite3_stmt *stmt, const char *iname, 
143
        int col_cnt, int row_cnt, int *dup_indices) {
151
        int col_cnt, int row_cnt, int *dup_indices) {
144
    SEXP ret, names, value, class = R_NilValue;
152
    SEXP ret, names, value, class = R_NilValue;
145
    int i, type;
153
    int i, type;
146
    const char *colname, *coltype;
154
    const char *colname, *coltype;
147
 
155
 
148
    PROTECT(ret = NEW_LIST(col_cnt));
156
    PROTECT(ret = NEW_LIST(col_cnt));
149
 
157
 
150
    /* set up names. */
158
    /* set up names. */
151
    PROTECT(names = NEW_CHARACTER(col_cnt));
159
    PROTECT(names = NEW_CHARACTER(col_cnt));
152
    for (i = 0; i < col_cnt; i++) {
160
    for (i = 0; i < col_cnt; i++) {
153
        colname = sqlite3_column_name(stmt, i+1);  /* +1 bec [row name is 0] */
161
        colname = sqlite3_column_name(stmt, i+1);  /* +1 bec [row name is 0] */
154
        coltype = sqlite3_column_decltype(stmt, i+1);
162
        coltype = sqlite3_column_decltype(stmt, i+1);
155
 
163
 
156
        if (dup_indices[i] == 0) {
164
        if (dup_indices[i] == 0) {
157
            strcpy(g_sql_buf[1], colname);
165
            strcpy(g_sql_buf[1], colname);
158
        } else {
166
        } else {
159
            sprintf(g_sql_buf[1], "%s.%d", colname, dup_indices[i]);
167
            sprintf(g_sql_buf[1], "%s.%d", colname, dup_indices[i]);
160
        }
168
        }
161
 
169
 
162
        SET_STRING_ELT(names, i, mkChar(g_sql_buf[1]));
170
        SET_STRING_ELT(names, i, mkChar(g_sql_buf[1]));
163
 
171
 
164
        if (strcmp(coltype, "text") == 0) {
172
        if (strcmp(coltype, "text") == 0) {
165
            PROTECT(value = NEW_CHARACTER(row_cnt));
173
            PROTECT(value = NEW_CHARACTER(row_cnt));
166
        } else if (strcmp(coltype, "double") == 0) {
174
        } else if (strcmp(coltype, "double") == 0) {
167
            PROTECT(value = NEW_NUMERIC(row_cnt));
175
            PROTECT(value = NEW_NUMERIC(row_cnt));
168
        } else if (strcmp(coltype, "bit") == 0) {
176
        } else if (strcmp(coltype, "bit") == 0) {
169
            PROTECT(value = NEW_LOGICAL(row_cnt));
177
            PROTECT(value = NEW_LOGICAL(row_cnt));
170
        } else if (strcmp(coltype, "integer") == 0 || 
178
        } else if (strcmp(coltype, "integer") == 0 || 
171
                   strcmp(coltype, "int") == 0) {
179
                   strcmp(coltype, "int") == 0) {
172
            PROTECT(value = NEW_INTEGER(row_cnt));
180
            PROTECT(value = NEW_INTEGER(row_cnt));
173
            type = _get_factor_levels1(iname, colname, value);
181
            type = _get_factor_levels1(iname, colname, value);
174
            if (type == VAR_FACTOR) {
182
            if (type == VAR_FACTOR) {
175
                PROTECT(class = mkString("factor"));
183
                PROTECT(class = mkString("factor"));
176
                SET_CLASS(value, class);
184
                SET_CLASS(value, class);
177
                UNPROTECT(1);
185
                UNPROTECT(1);
178
            } else if (type == VAR_ORDERED) {
186
            } else if (type == VAR_ORDERED) {
179
                PROTECT(class = NEW_CHARACTER(2));
187
                PROTECT(class = NEW_CHARACTER(2));
180
                SET_STRING_ELT(class, 0, mkChar("ordered"));
188
                SET_STRING_ELT(class, 0, mkChar("ordered"));
181
                SET_STRING_ELT(class, 1, mkChar("factor"));
189
                SET_STRING_ELT(class, 1, mkChar("factor"));
182
                SET_CLASS(value, class);
190
                SET_CLASS(value, class);
183
                UNPROTECT(1);
191
                UNPROTECT(1);
184
            }
192
            }
185
        } else {
193
        } else {
186
            Rprintf("Error: not supported type %s for %s\n", coltype, colname);
194
            Rprintf("Error: not supported type %s for %s\n", coltype, colname);
187
            UNPROTECT(2); /* unprotect ret, names */
195
            UNPROTECT(2); /* unprotect ret, names */
188
            return R_NilValue;
196
            return R_NilValue;
189
        }
197
        }
190
 
198
 
191
        SET_VECTOR_ELT(ret, i, value);
199
        SET_VECTOR_ELT(ret, i, value);
192
        UNPROTECT(1); /* unprotect value */
200
        UNPROTECT(1); /* unprotect value */
193
                    
201
                    
194
    }
202
    }
195
    SET_NAMES(ret, names);
203
    SET_NAMES(ret, names);
196
    UNPROTECT(1); /* unprotect names only */
204
    UNPROTECT(1); /* unprotect names only */
197
    return ret;
205
    return ret;
198
}
206
}
199
 
207
 
200
/* expected that 1st col of stmt is [row name], so we start with index 1 */
208
/* expected that 1st col of stmt is [row name], so we start with index 1 */
201
static int _add_row_to_df(SEXP df, sqlite3_stmt *stmt, int row, int ncols) {
209
static int _add_row_to_df(SEXP df, sqlite3_stmt *stmt, int row, int ncols) {
202
    SEXP vec;
210
    SEXP vec;
203
    int type = -1, is_null, i;
211
    int type = -1, is_null, i;
204
    for (i = 1; i <= ncols; i++) {
212
    for (i = 1; i <= ncols; i++) {
205
        vec = VECTOR_ELT(df, i-1);
213
        vec = VECTOR_ELT(df, i-1);
206
        type = TYPEOF(vec);
214
        type = TYPEOF(vec);
207
 
215
 
208
        is_null = (sqlite3_column_type(stmt, row) == SQLITE_NULL);
216
        is_null = (sqlite3_column_type(stmt, row) == SQLITE_NULL);
209
 
217
 
210
        if (type == STRSXP || type == CHARSXP) {
218
        if (type == STRSXP || type == CHARSXP) {
211
            SET_STRING_ELT(vec, row, mkChar((char *)sqlite3_column_text(stmt, i)));
219
            SET_STRING_ELT(vec, row, mkChar((char *)sqlite3_column_text(stmt, i)));
212
        } else if (type == INTSXP) {
220
        } else if (type == INTSXP) {
213
            INTEGER(vec)[row] = sqlite3_column_int(stmt, i);
221
            INTEGER(vec)[row] = sqlite3_column_int(stmt, i);
214
        } else if (type == REALSXP) {
222
        } else if (type == REALSXP) {
215
            REAL(vec)[row] = sqlite3_column_double(stmt, i);
223
            REAL(vec)[row] = sqlite3_column_double(stmt, i);
216
        } else if (type == LGLSXP) {
224
        } else if (type == LGLSXP) {
217
            LOGICAL(vec)[row] = sqlite3_column_int(stmt, i);
225
            LOGICAL(vec)[row] = sqlite3_column_int(stmt, i);
218
        }
226
        }
219
    }
227
    }
220
    return type;
228
    return type;
221
}
229
}
222
 
230
 
223
/* set ordinary df row name as numbers */
231
/* set ordinary df row name as numbers */
224
static void _set_rownames2(SEXP df) {
232
static void _set_rownames2(SEXP df) {
225
    SEXP value = VECTOR_ELT(df, 0);
233
    SEXP value = VECTOR_ELT(df, 0);
226
    int len = LENGTH(value), i;
234
    int len = LENGTH(value), i;
227
    PROTECT(value = NEW_CHARACTER(len));
235
    PROTECT(value = NEW_CHARACTER(len));
228
    for (i = 0; i < len; i++) {
236
    for (i = 0; i < len; i++) {
229
        sprintf(g_sql_buf[2], "%d", i+1);
237
        sprintf(g_sql_buf[2], "%d", i+1);
230
        SET_STRING_ELT(value, i, mkChar(g_sql_buf[2]));
238
        SET_STRING_ELT(value, i, mkChar(g_sql_buf[2]));
231
    }
239
    }
232
 
240
 
233
    SET_ROWNAMES(df, value);
241
    SET_ROWNAMES(df, value);
234
    UNPROTECT(1);
242
    UNPROTECT(1);
235
}
243
}
236
 
244
 
237
 
245
 
238
/****************************************************************************
246
/****************************************************************************
239
 * SDF FUNCTIONS
247
 * SDF FUNCTIONS
240
 ****************************************************************************/
248
 ****************************************************************************/
241
 
249
 
242
SEXP sdf_create_sdf(SEXP df, SEXP name) {
250
SEXP sdf_create_sdf(SEXP df, SEXP name) {
243
    SEXP ret;
251
    SEXP ret;
244
    char *iname; 
252
    char *iname; 
245
    int namelen, res, i, j;
253
    int namelen, res, i, j;
246
 
254
 
247
    /* find free name, attach sdf, create sdf_attributes */
255
    /* find free name, attach sdf, create sdf_attributes */
248
    iname = _create_sdf_skeleton1(name, &namelen, FALSE);
256
    iname = _create_sdf_skeleton1(name, &namelen, FALSE);
249
    
257
    
250
    if (iname != NULL) {
258
    if (iname != NULL) {
251
        int sql_len, sql_len2;
259
        int sql_len, sql_len2;
252
        sqlite3_stmt *stmt;
260
        sqlite3_stmt *stmt;
253
 
261
 
254
        /* create sdf_data table */
262
        /* create sdf_data table */
255
        SEXP names = GET_NAMES(df), variable, levels, var_class;
263
        SEXP names = GET_NAMES(df), variable, levels, var_class;
256
        int ncols = GET_LENGTH(names), type, *types;
264
        int ncols = GET_LENGTH(names), type, *types;
257
        char *col_name, *class, *factor;
265
        char *col_name, *class, *factor;
258
 
266
 
259
        /* variables for adding rownames */
267
        /* variables for adding rownames */
260
        SEXP rownames;
268
        SEXP rownames;
261
        int nrows;
269
        int nrows;
262
        char *row_name;
270
        char *row_name;
263
 
271
 
264
        /* TODO: put constraints on table after inserting everything? */
272
        /* TODO: put constraints on table after inserting everything? */
265
 
273
 
266
 
274
 
267
        /* 
275
        /* 
268
         * create the create table and insert sql scripts by looping through
276
         * create the create table and insert sql scripts by looping through
269
         * the columns of df
277
         * the columns of df
270
         */
278
         */
271
        types = (int *)R_alloc(ncols, sizeof(int));
279
        types = (int *)R_alloc(ncols, sizeof(int));
272
        sql_len = sprintf(g_sql_buf[0], "create table [%s].sdf_data ([row name] text", iname);
280
        sql_len = sprintf(g_sql_buf[0], "create table [%s].sdf_data ([row name] text", iname);
273
        sql_len2 = sprintf(g_sql_buf[1], "insert into [%s].sdf_data values(?", iname);
281
        sql_len2 = sprintf(g_sql_buf[1], "insert into [%s].sdf_data values(?", iname);
274
 
282
 
275
        for (i = 0; i < ncols; i++) {
283
        for (i = 0; i < ncols; i++) {
276
            col_name = CHAR(STRING_ELT(names, i));
284
            col_name = CHAR(STRING_ELT(names, i));
277
 
285
 
278
            /* add column definition to the create table sql */
286
            /* add column definition to the create table sql */
279
            _expand_buf(0, sql_len+strlen(col_name)+10);
287
            _expand_buf(0, sql_len+strlen(col_name)+10);
280
 
288
 
281
            variable = _getListElement(df, col_name);
289
            variable = _getListElement(df, col_name);
282
            var_class = GET_CLASS(variable);
290
            var_class = GET_CLASS(variable);
283
            class = (var_class == R_NilValue) ? NULL : CHAR(STRING_ELT(var_class, 0));
291
            class = (var_class == R_NilValue) ? NULL : CHAR(STRING_ELT(var_class, 0));
284
            type = TYPEOF(variable);
292
            type = TYPEOF(variable);
285
            types[i] = type;
293
            types[i] = type;
286
 
294
 
287
            sql_len += sprintf(g_sql_buf[0]+sql_len, ", [%s] %s", col_name, 
295
            sql_len += sprintf(g_sql_buf[0]+sql_len, ", [%s] %s", col_name, 
288
                    _get_column_type(class, type));
296
                    _get_column_type(class, type));
289
 
297
 
290
            /* add handler to insert table sql */
298
            /* add handler to insert table sql */
291
            _expand_buf(1, sql_len+5);
299
            _expand_buf(1, sql_len+5);
292
            strcpy(g_sql_buf[1]+sql_len2, ",?");
300
            strcpy(g_sql_buf[1]+sql_len2, ",?");
293
            sql_len2 += 2; 
301
            sql_len2 += 2; 
294
 
302
 
295
            /* create separate table for factors decode */
303
            /* create separate table for factors decode */
296
            if (class != NULL && (strcmp(class, "factor") == 0 || strcmp(class, "ordered") == 0)){
304
            if (class != NULL && (strcmp(class, "factor") == 0 || strcmp(class, "ordered") == 0)){
297
                if (_create_factor_table2(iname, class, col_name)) 
305
                if (_create_factor_table2(iname, class, col_name)) 
298
                    return R_NilValue; /* dup tbl name? */
306
                    return R_NilValue; /* dup tbl name? */
299
 
307
 
300
                _sqlite_exec("begin");
308
                _sqlite_exec("begin");
301
                levels = GET_LEVELS(variable);
309
                levels = GET_LEVELS(variable);
302
                sprintf(g_sql_buf[2], "insert into [%s].[%s %s] values(?, ?);",
310
                sprintf(g_sql_buf[2], "insert into [%s].[%s %s] values(?, ?);",
303
                        iname, class, col_name);
311
                        iname, class, col_name);
304
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
312
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
305
                if (_sqlite_error(res)) return R_NilValue; /* dup tbl name? */
313
                if (_sqlite_error(res)) return R_NilValue; /* dup tbl name? */
306
 
314
 
307
                for (j = 0; j < GET_LENGTH(levels); j++) {
315
                for (j = 0; j < GET_LENGTH(levels); j++) {
308
                    sqlite3_reset(stmt);
316
                    sqlite3_reset(stmt);
309
                    factor = CHAR(STRING_ELT(levels, j));
317
                    factor = CHAR(STRING_ELT(levels, j));
310
                    sqlite3_bind_int(stmt, 1, j+1);
318
                    sqlite3_bind_int(stmt, 1, j+1);
311
                    sqlite3_bind_text(stmt, 2, factor, -1, SQLITE_STATIC);
319
                    sqlite3_bind_text(stmt, 2, factor, -1, SQLITE_STATIC);
312
                    sqlite3_step(stmt);
320
                    sqlite3_step(stmt);
313
                }
321
                }
314
                sqlite3_finalize(stmt);
322
                sqlite3_finalize(stmt);
315
                _sqlite_exec("commit");
323
                _sqlite_exec("commit");
316
            }
324
            }
317
        }
325
        }
318
        
326
        
319
        _expand_buf(0,sql_len+35);
327
        _expand_buf(0,sql_len+35);
320
        sql_len += sprintf(g_sql_buf[0]+sql_len, ", primary key([row name]));");
328
        sql_len += sprintf(g_sql_buf[0]+sql_len, ", primary key([row name]));");
321
        /* sql_len += sprintf(g_sql_buf[0]+sql_len, ");"); */
329
        /* sql_len += sprintf(g_sql_buf[0]+sql_len, ");"); */
322
        res = _sqlite_exec(g_sql_buf[0]);
330
        res = _sqlite_exec(g_sql_buf[0]);
323
        if (_sqlite_error(res)) return R_NilValue; /* why? */
331
        if (_sqlite_error(res)) return R_NilValue; /* why? */
324
 
332
 
325
        /*
333
        /*
326
         * add the data in df to the sdf
334
         * add the data in df to the sdf
327
         */
335
         */
328
        rownames = getAttrib(df, R_RowNamesSymbol);
336
        rownames = getAttrib(df, R_RowNamesSymbol);
329
        nrows = GET_LENGTH(rownames);
337
        nrows = GET_LENGTH(rownames);
330
 
338
 
331
        _sqlite_error(_sqlite_exec("begin"));
339
        _sqlite_error(_sqlite_exec("begin"));
332
        sprintf(g_sql_buf[1]+sql_len2, ")");
340
        sprintf(g_sql_buf[1]+sql_len2, ")");
333
        res = sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
341
        res = sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
334
 
342
 
335
        for (i = 0; i < nrows; i++) {
343
        for (i = 0; i < nrows; i++) {
336
            sqlite3_reset(stmt);
344
            sqlite3_reset(stmt);
337
 
345
 
338
            /* since this is coming from a real dataframe, we're assured that
346
            /* since this is coming from a real dataframe, we're assured that
339
             * the rownames are unique */
347
             * the rownames are unique */
340
            if (IS_CHARACTER(rownames)) {
348
            if (IS_CHARACTER(rownames)) {
341
                row_name = CHAR(STRING_ELT(rownames, i));
349
                row_name = CHAR(STRING_ELT(rownames, i));
342
                if (*row_name) /* if not empty string */
350
                if (*row_name) /* if not empty string */
343
                    sqlite3_bind_text(stmt, 1, row_name, strlen(row_name), SQLITE_STATIC);
351
                    sqlite3_bind_text(stmt, 1, row_name, strlen(row_name), SQLITE_STATIC);
344
                else sqlite3_bind_int(stmt, 1, i);
352
                else sqlite3_bind_int(stmt, 1, i);
345
            } else if (IS_INTEGER(rownames)) {
353
            } else if (IS_INTEGER(rownames)) {
346
                sqlite3_bind_int(stmt, 1, INTEGER(rownames)[i]);
354
                sqlite3_bind_int(stmt, 1, INTEGER(rownames)[i]);
347
            } else sqlite3_bind_int(stmt, 1, i);
355
            } else sqlite3_bind_int(stmt, 1, i);
348
 
356
 
349
            for (j = 0; j < ncols; j++) {
357
            for (j = 0; j < ncols; j++) {
350
                variable = VECTOR_ELT(df, j);
358
                variable = VECTOR_ELT(df, j);
351
                switch(types[j]) {
359
                switch(types[j]) {
352
                    case INTSXP : 
360
                    case INTSXP : 
353
                        sqlite3_bind_int(stmt, j+2, INTEGER(variable)[i]);
361
                        sqlite3_bind_int(stmt, j+2, INTEGER(variable)[i]);
354
                        break;
362
                        break;
355
                    case REALSXP:
363
                    case REALSXP:
356
                        sqlite3_bind_double(stmt, j+2, REAL(variable)[i]);
364
                        sqlite3_bind_double(stmt, j+2, REAL(variable)[i]);
357
                        break;
365
                        break;
358
                    case CHARSXP:
366
                    case CHARSXP:
359
                    case STRSXP:
367
                    case STRSXP:
360
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(variable, i), -1, SQLITE_STATIC);
368
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(variable, i), -1, SQLITE_STATIC);
361
                }
369
                }
362
                /* TODO: handle NA's & NULL's */
370
                /* TODO: handle NA's & NULL's */
363
            }
371
            }
364
 
372
 
365
            res = sqlite3_step(stmt);
373
            res = sqlite3_step(stmt);
366
            if (res != SQLITE_DONE) { 
374
            if (res != SQLITE_DONE) { 
367
                _sqlite_exec("ROLLBACK");
375
                _sqlite_exec("ROLLBACK");
368
                sqlite3_finalize(stmt);
376
                sqlite3_finalize(stmt);
369
                Rprintf("SQLITE ERROR: %s\n", sqlite3_errmsg(g_workspace));
377
                Rprintf("SQLITE ERROR: %s\n", sqlite3_errmsg(g_workspace));
370
                return R_NilValue; /* why? */
378
                return R_NilValue; /* why? */
371
            }
379
            }
372
        }
380
        }
373
                
381
                
374
        sqlite3_finalize(stmt);
382
        sqlite3_finalize(stmt);
375
        _sqlite_error(_sqlite_exec("COMMIT"));
383
        _sqlite_error(_sqlite_exec("COMMIT"));
376
 
384
 
377
        /* create a new object representing the sdf */
385
        /* create a new object representing the sdf */
378
        ret = _create_sdf_sexp(iname);
386
        ret = _create_sdf_sexp(iname);
379
 
387
 
380
    } else {
388
    } else {
381
        Rprintf("ERROR: unable to create a sqlite data frame.\n");
389
        Rprintf("ERROR: unable to create a sqlite data frame.\n");
382
        ret = R_NilValue;
390
        ret = R_NilValue;
383
    }
391
    }
384
        
392
        
385
    return ret;
393
    return ret;
386
}
394
}
387
 
395
 
388
SEXP sdf_get_names(SEXP sdf) {
396
SEXP sdf_get_names(SEXP sdf) {
389
    char *iname;
397
    char *iname;
390
    iname = SDF_INAME(sdf);
398
    iname = SDF_INAME(sdf);
391
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
399
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
392
 
400
 
393
    int len;
401
    int len;
394
    len = sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
402
    len = sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
395
 
403
 
396
    sqlite3_stmt *stmt;
404
    sqlite3_stmt *stmt;
397
    int res, i;
405
    int res, i;
398
   
406
   
399
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], len, &stmt, NULL);
407
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], len, &stmt, NULL);
400
    if (_sqlite_error(res)) return R_NilValue;
408
    if (_sqlite_error(res)) return R_NilValue;
401
 
409
 
402
    SEXP ret;
410
    SEXP ret;
403
 
411
 
404
    len = sqlite3_column_count(stmt)-1;
412
    len = sqlite3_column_count(stmt)-1;
405
    PROTECT(ret = NEW_CHARACTER(len));
413
    PROTECT(ret = NEW_CHARACTER(len));
406
 
414
 
407
    for (i = 0; i < len; i++) {
415
    for (i = 0; i < len; i++) {
408
        SET_STRING_ELT(ret, i, mkChar(sqlite3_column_name(stmt, i+1)));
416
        SET_STRING_ELT(ret, i, mkChar(sqlite3_column_name(stmt, i+1)));
409
    }
417
    }
410
 
418
 
411
    sqlite3_finalize(stmt);
419
    sqlite3_finalize(stmt);
412
    UNPROTECT(1);
420
    UNPROTECT(1);
413
    return ret;
421
    return ret;
414
}
422
}
415
 
423
 
416
SEXP sdf_get_length(SEXP sdf) {
424
SEXP sdf_get_length(SEXP sdf) {
417
    char *iname;
425
    char *iname;
418
    int len;
426
    int len;
419
    sqlite3_stmt *stmt;
427
    sqlite3_stmt *stmt;
420
    int res;
428
    int res;
421
 
429
 
422
    iname  = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
430
    iname  = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
423
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
431
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
424
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
432
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
425
 
433
 
426
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
434
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
427
    if (_sqlite_error(res)) return R_NilValue;
435
    if (_sqlite_error(res)) return R_NilValue;
428
 
436
 
429
    len = sqlite3_column_count(stmt)-1;
437
    len = sqlite3_column_count(stmt)-1;
430
    sqlite3_finalize(stmt);
438
    sqlite3_finalize(stmt);
431
    return ScalarInteger(len);
439
    return ScalarInteger(len);
432
}
440
}
433
 
441
 
434
/* get row count */
442
/* get row count */
435
SEXP sdf_get_row_count(SEXP sdf) {
443
SEXP sdf_get_row_count(SEXP sdf) {
436
    char *iname = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
444
    char *iname = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
437
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
445
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
438
 
446
 
439
    int nrow;
447
    int nrow;
440
    SEXP ret;
448
    SEXP ret;
441
   
449
   
442
    nrow = _get_row_count2(iname, TRUE);
450
    nrow = _get_row_count2(iname, TRUE);
443
 
451
 
444
    if (nrow < 1) ret = R_NilValue;
452
    if (nrow < 1) ret = R_NilValue;
445
    else ret = ScalarInteger(nrow);
453
    else ret = ScalarInteger(nrow);
446
 
454
 
447
    return ret;
455
    return ret;
448
}
456
}
449
 
457
 
450
    
458
    
451
SEXP sdf_import_table(SEXP _filename, SEXP _name, SEXP _sep, SEXP _quote, 
459
SEXP sdf_import_table(SEXP _filename, SEXP _name, SEXP _sep, SEXP _quote, 
452
        SEXP _rownames, SEXP _colnames) {
460
        SEXP _rownames, SEXP _colnames) {
453
    char *filename = CHAR_ELT(_filename, 0);
461
    char *filename = CHAR_ELT(_filename, 0);
454
    FILE *f = fopen(filename, "r");
462
    FILE *f = fopen(filename, "r");
455
 
463
 
456
    if (f == NULL) {
464
    if (f == NULL) {
457
        Rprintf("Error: File %s does not exist.", filename);
465
        Rprintf("Error: File %s does not exist.", filename);
458
        return R_NilValue;
466
        return R_NilValue;
459
    }
467
    }
460
 
468
 
461
    /*char *sep = CHAR_ELT(_sep, 0), *quote = CHAR_ELT(_quote,0);
469
    /*char *sep = CHAR_ELT(_sep, 0), *quote = CHAR_ELT(_quote,0);
462
    char *name = CHAR_ELT(_name, 0);*/
470
    char *name = CHAR_ELT(_name, 0);*/
463
 
471
 
464
    /* create the table */
472
    /* create the table */
465
    /* insert the stuffs */
473
    /* insert the stuffs */
466
    /* register to workspace */
474
    /* register to workspace */
467
 
475
 
468
    return R_NilValue;
476
    return R_NilValue;
469
}
477
}
470
 
478
 
471
SEXP sdf_get_index(SEXP sdf, SEXP row, SEXP col) {
479
SEXP sdf_get_index(SEXP sdf, SEXP row, SEXP col, SEXP new_sdf) {
472
    SEXP ret = R_NilValue;
480
    SEXP ret = R_NilValue;
473
    char *iname = SDF_INAME(sdf);
481
    char *iname = SDF_INAME(sdf);
474
    if (!USE_SDF1(iname, TRUE, TRUE)) return R_NilValue;
-
 
475
 
-
 
476
    sqlite3_stmt *stmt;
482
    sqlite3_stmt *stmt;
477
    int buflen = 0, idxlen, col_cnt, row_cnt, index;
483
    int buflen = 0, idxlen, col_cnt, row_cnt, index;
478
    int i, j,res;
484
    int i, j,res;
479
    int *col_indices, col_index_len, *dup_indices;
485
    int *col_indices, col_index_len, *dup_indices;
480
    int row_index_len = 0;
486
    int row_index_len = 0, force_new_df = LOGICAL(new_sdf)[0];
-
 
487
 
-
 
488
    if (!USE_SDF1(iname, TRUE, TRUE)) return R_NilValue;
481
 
489
 
482
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data ", iname);
490
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data ", iname);
483
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
491
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
484
    if (_sqlite_error(res)) return R_NilValue;
492
    if (_sqlite_error(res)) return R_NilValue;
485
 
493
 
486
    buflen = sprintf(g_sql_buf[0], "select [row name]");
494
    buflen = sprintf(g_sql_buf[0], "select [row name]");
487
    idxlen = LENGTH(col);
495
    idxlen = LENGTH(col);
488
    col_cnt = sqlite3_column_count(stmt) - 1;
496
    col_cnt = sqlite3_column_count(stmt) - 1;
489
 
497
 
490
    /*
498
    /*
491
     * PROCESS COLUMN INDEX: set columns in the select statement
499
     * PROCESS COLUMN INDEX: set columns in the select statement
492
     */
500
     */
493
    if (col == R_NilValue) {
501
    if (col == R_NilValue) {
494
        for (i = 1; i < col_cnt+1; i++) {
502
        for (i = 1; i < col_cnt+1; i++) {
495
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
503
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
496
                    sqlite3_column_name(stmt, i)); 
504
                    sqlite3_column_name(stmt, i)); 
497
        }
505
        }
498
        _expand_buf(0, buflen+20+strlen(iname));
506
        _expand_buf(0, buflen+20+strlen(iname));
499
        buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
507
        buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
500
        col_index_len = col_cnt;
508
        col_index_len = col_cnt;
501
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
509
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
502
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
510
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
503
        for (i = 0; i < col_cnt; i++) { col_indices[i] = i; dup_indices[i] = 0; }
511
        for (i = 0; i < col_cnt; i++) { col_indices[i] = i; dup_indices[i] = 0; }
504
    } else if (col == R_NilValue || idxlen < 1) {
512
    } else if (col == R_NilValue || idxlen < 1) {
505
        sqlite3_finalize(stmt);
513
        sqlite3_finalize(stmt);
506
        return R_NilValue;
514
        return R_NilValue;
507
    } else if (IS_NUMERIC(col)) {
515
    } else if (IS_NUMERIC(col)) {
508
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
516
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
509
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
517
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
510
        col_index_len = 0;
518
        col_index_len = 0;
511
 
519
 
512
        for (i = 0; i < idxlen; i++) {
520
        for (i = 0; i < idxlen; i++) {
513
            /* no need to correct for 0 base because col 0 is [row name] */
521
            /* no need to correct for 0 base because col 0 is [row name] */
514
            index = ((int) REAL(col)[i]); 
522
            index = ((int) REAL(col)[i]); 
515
            if (index > col_cnt) {
523
            if (index > col_cnt) {
516
                sqlite3_finalize(stmt);
524
                sqlite3_finalize(stmt);
517
                Rprintf("Error: undefined columns selected\n");
525
                Rprintf("Error: undefined columns selected\n");
518
                return R_NilValue;
526
                return R_NilValue;
519
            } else if (index > 0) {
527
            } else if (index > 0) {
520
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
528
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
521
                        sqlite3_column_name(stmt,index));
529
                        sqlite3_column_name(stmt,index));
522
                dup_indices[col_index_len] = 0;
530
                dup_indices[col_index_len] = 0;
523
                for (j = 0; j < col_index_len; j++) {
531
                for (j = 0; j < col_index_len; j++) {
524
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
532
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
525
                }
533
                }
526
                col_indices[col_index_len++] = index;
534
                col_indices[col_index_len++] = index;
527
            } else if (index < 0) {
535
            } else if (index < 0) {
528
                sqlite3_finalize(stmt);
536
                sqlite3_finalize(stmt);
529
                Rprintf("Error: negative indices not supported.\n");
537
                Rprintf("Error: negative indices not supported.\n");
530
                return R_NilValue;
538
                return R_NilValue;
531
            }
539
            }
532
        }
540
        }
533
 
541
 
534
        if (col_index_len == 0) {
542
        if (col_index_len == 0) {
535
            sqlite3_finalize(stmt);
543
            sqlite3_finalize(stmt);
536
            Rprintf("Error: no indices detected??\n");
544
            Rprintf("Error: no indices detected??\n");
537
            return R_NilValue;
545
            return R_NilValue;
538
        } else { 
546
        } else { 
539
            _expand_buf(0, buflen+20+strlen(iname));
547
            _expand_buf(0, buflen+20+strlen(iname));
540
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
548
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
541
        }
549
        }
542
    } else if (IS_INTEGER(col)) {
550
    } else if (IS_INTEGER(col)) {
543
        /* identical logic with IS_NUMERIC, except that we don't have to cast
551
        /* identical logic with IS_NUMERIC, except that we don't have to cast
544
         * stuffs from SEXP col. the alternative is doing if idxlen times. */
552
         * stuffs from SEXP col. the alternative is doing if idxlen times. */
545
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
553
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
546
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
554
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
547
        col_index_len = 0;
555
        col_index_len = 0;
548
 
556
 
549
        for (i = 0; i < idxlen; i++) {
557
        for (i = 0; i < idxlen; i++) {
550
            /* no need to correct for 0 base because col 0 is [row name] */
558
            /* no need to correct for 0 base because col 0 is [row name] */
551
            index = INTEGER(col)[i];
559
            index = INTEGER(col)[i];
552
            if (index > col_cnt) {
560
            if (index > col_cnt) {
553
                sqlite3_finalize(stmt);
561
                sqlite3_finalize(stmt);
554
                Rprintf("Error: undefined columns selected\n");
562
                Rprintf("Error: undefined columns selected\n");
555
                return R_NilValue;
563
                return R_NilValue;
556
            } else if (index > 0) {
564
            } else if (index > 0) {
557
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
565
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
558
                        sqlite3_column_name(stmt,index));
566
                        sqlite3_column_name(stmt,index));
559
                dup_indices[col_index_len] = 0;
567
                dup_indices[col_index_len] = 0;
560
                for (j = 0; j < col_index_len; j++) {
568
                for (j = 0; j < col_index_len; j++) {
561
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
569
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
562
                }
570
                }
563
                col_indices[col_index_len++] = index;
571
                col_indices[col_index_len++] = index;
564
            } else if (index < 0) {
572
            } else if (index < 0) {
565
                sqlite3_finalize(stmt);
573
                sqlite3_finalize(stmt);
566
                Rprintf("Error: negative indices not supported.\n");
574
                Rprintf("Error: negative indices not supported.\n");
567
                return R_NilValue;
575
                return R_NilValue;
568
            }
576
            }
569
        }
577
        }
570
 
578
 
571
        if (col_index_len == 0) {
579
        if (col_index_len == 0) {
572
            sqlite3_finalize(stmt);
580
            sqlite3_finalize(stmt);
573
            Rprintf("Error: no indices detected??\n");
581
            Rprintf("Error: no indices detected??\n");
574
            return R_NilValue;
582
            return R_NilValue;
575
        } else { 
583
        } else { 
576
            _expand_buf(0, buflen+20+strlen(iname));
584
            _expand_buf(0, buflen+20+strlen(iname));
577
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
585
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
578
        }
586
        }
579
    } else if (IS_LOGICAL(col)) {
587
    } else if (IS_LOGICAL(col)) {
580
        /* recycling stuff, so max column output is the # of cols in the df */
588
        /* recycling stuff, so max column output is the # of cols in the df */
581
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
589
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
582
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
590
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
583
        col_index_len = 0;
591
        col_index_len = 0;
584
        for (i = 0; i < col_cnt; i++) {
592
        for (i = 0; i < col_cnt; i++) {
585
            if (LOGICAL(col)[i%idxlen]) {
593
            if (LOGICAL(col)[i%idxlen]) {
586
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
594
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
587
                        sqlite3_column_name(stmt,i+1));
595
                        sqlite3_column_name(stmt,i+1));
588
                dup_indices[col_index_len] = 0;
596
                dup_indices[col_index_len] = 0;
589
                col_indices[col_index_len++] = i;
597
                col_indices[col_index_len++] = i;
590
            }
598
            }
591
        }
599
        }
592
 
600
 
593
        if (col_index_len == 0) {
601
        if (col_index_len == 0) {
594
            sqlite3_finalize(stmt);
602
            sqlite3_finalize(stmt);
595
            Rprintf("Warning: no column selected.\n");
603
            Rprintf("Warning: no column selected.\n");
596
            return R_NilValue;
604
            return R_NilValue;
597
        } else { 
605
        } else { 
598
            _expand_buf(0, buflen+20+strlen(iname));
606
            _expand_buf(0, buflen+20+strlen(iname));
599
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
607
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
600
        }
608
        }
601
    } else {
609
    } else {
602
        sqlite3_finalize(stmt);
610
        sqlite3_finalize(stmt);
603
        Rprintf("Error: don't know how to handle column index.\n");
611
        Rprintf("Error: don't know how to handle column index.\n");
604
        return R_NilValue;
612
        return R_NilValue;
605
    }
613
    }
606
 
614
 
607
    /* 
615
    /* 
608
     * PROCESS ROW INDEX: setup limit or where clause
616
     * PROCESS ROW INDEX: setup limit or where clause
609
     */
617
     */
610
    idxlen = LENGTH(row);
618
    idxlen = LENGTH(row);
611
    if (row == R_NilValue) {
619
    if (row == R_NilValue) {
612
        if (col_index_len == 1) {
620
        if (col_index_len == 1 && !force_new_df) {
613
            ret = sdf_get_variable(sdf, mkString(sqlite3_column_name(stmt,col_indices[0])));
621
            ret = sdf_get_variable(sdf, mkString(sqlite3_column_name(stmt,col_indices[0])));
614
            sqlite3_finalize(stmt);
622
            sqlite3_finalize(stmt);
615
            return ret;
623
            return ret;
616
        } if (col_index_len > 1) {
624
        } if (col_index_len > 1 || (force_new_df && col_index_len == 1)) {
617
            /* create a new SDF, logic similar to sdf_create_sdf */
625
            /* create a new SDF, logic similar to sdf_create_sdf */
618
 
626
 
619
            /* find a new name. data<n> ? */
627
            /* find a new name. data<n> ? */
620
            char *iname2;
628
            char *iname2;
621
            const char *colname;
629
            const char *colname;
622
            int namelen, sql_len, sql_len2;
630
            int namelen, sql_len, sql_len2;
623
 
631
 
624
            iname2 = _create_sdf_skeleton1(R_NilValue, &namelen, TRUE);
632
            iname2 = _create_sdf_skeleton1(R_NilValue, &namelen, TRUE);
625
 
633
 
626
            /* create sdf_data table */
634
            /* create sdf_data table */
627
            sql_len = sprintf(g_sql_buf[1], "create table [%s].sdf_data ([row name] text", iname2);
635
            sql_len = sprintf(g_sql_buf[1], "create table [%s].sdf_data ([row name] text", iname2);
628
            sql_len2 = 0;
636
            sql_len2 = 0;
629
 
637
 
630
            for (i = 0; i < col_index_len; i++) {
638
            for (i = 0; i < col_index_len; i++) {
631
                colname = sqlite3_column_name(stmt, col_indices[i]);
639
                colname = sqlite3_column_name(stmt, col_indices[i]);
632
                if (dup_indices[i] == 0) {
640
                if (dup_indices[i] == 0) {
633
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s] %s", colname,
641
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s] %s", colname,
634
                            sqlite3_column_decltype(stmt, col_indices[i]));
642
                            sqlite3_column_decltype(stmt, col_indices[i]));
635
                } else {
643
                } else {
636
                    /* un-duplicate col names by appending num, just like R */
644
                    /* un-duplicate col names by appending num, just like R */
637
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s.%d] %s", colname,
645
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s.%d] %s", colname,
638
                            dup_indices[i], 
646
                            dup_indices[i], 
639
                            sqlite3_column_decltype(stmt, col_indices[i]));
647
                            sqlite3_column_decltype(stmt, col_indices[i]));
640
                }
648
                }
641
 
649
 
642
                /* deal with possibly factor columns */
650
                /* deal with possibly factor columns */
643
                if (_is_factor2(iname, "factor", colname)) {
651
                if (_is_factor2(iname, "factor", colname)) {
644
                    /* found a factor column */
652
                    /* found a factor column */
645
 
653
 
646
                    if (dup_indices[i] == 0)  {
654
                    if (dup_indices[i] == 0)  {
647
                        _copy_factor_levels2("factor", iname, colname, iname2, colname);
655
                        _copy_factor_levels2("factor", iname, colname, iname2, colname);
648
                    } else {
656
                    } else {
649
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
657
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
650
                        _copy_factor_levels2("factor", iname, colname, iname2, 
658
                        _copy_factor_levels2("factor", iname, colname, iname2, 
651
                                g_sql_buf[3]);
659
                                g_sql_buf[3]);
652
                    }
660
                    }
653
                }
661
                }
654
 
662
 
655
                /* and deal with ordered factors too... life is hard, then you die */
663
                /* and deal with ordered factors too... life is hard, then you die */
656
                if (_is_factor2(iname, "ordered", colname)) {
664
                if (_is_factor2(iname, "ordered", colname)) {
657
                    
665
                    
658
                    if (dup_indices[i] == 0)  {
666
                    if (dup_indices[i] == 0)  {
659
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
667
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
660
                                colname);
668
                                colname);
661
                    } else {
669
                    } else {
662
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
670
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
663
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
671
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
664
                                g_sql_buf[3]);
672
                                g_sql_buf[3]);
665
                    }
673
                    }
666
                }
674
                }
667
                                
675
                                
668
            }
676
            }
669
 
677
 
670
            /* don't need it anymore */
678
            /* don't need it anymore */
671
            sqlite3_finalize(stmt);
679
            sqlite3_finalize(stmt);
672
 
680
 
673
            /* no table index created, that's for v2 I hope*/
681
            /* no table index created, that's for v2 I hope*/
674
            sql_len += sprintf(g_sql_buf[1]+sql_len, ");");
682
            sql_len += sprintf(g_sql_buf[1]+sql_len, ");");
675
            res = _sqlite_exec(g_sql_buf[1]);
683
            res = _sqlite_exec(g_sql_buf[1]);
676
            if (_sqlite_error(res)) { Rprintf("here? %s\n", g_sql_buf[1]); return R_NilValue; }
684
            if (_sqlite_error(res)) { Rprintf("here? %s\n", g_sql_buf[1]); return R_NilValue; }
677
 
685
 
678
            /* insert data (with row names). buf[0] contains a select */
686
            /* insert data (with row names). buf[0] contains a select */
679
            sprintf(g_sql_buf[1], "insert into [%s].sdf_data %s", iname2,
687
            sprintf(g_sql_buf[1], "insert into [%s].sdf_data %s", iname2,
680
                    g_sql_buf[0]);
688
                    g_sql_buf[0]);
681
            res = _sqlite_exec(g_sql_buf[1]);
689
            res = _sqlite_exec(g_sql_buf[1]);
682
            if (_sqlite_error(res)) return R_NilValue;
690
            if (_sqlite_error(res)) return R_NilValue;
683
 
691
 
684
            /* add new sdf to workspace */
-
 
685
            sprintf(g_sql_buf[0], "%s.db", iname2);
-
 
686
            res = _add_sdf1(g_sql_buf[0], iname2);
-
 
687
            if (_sqlite_error(res)) return R_NilValue;
-
 
688
 
-
 
689
            /* remove protection */
692
            /* remove protection */
690
            UNUSE_SDF2(iname2);
693
            UNUSE_SDF2(iname2);
691
 
694
 
692
            /* create SEXP for the SDF */
695
            /* create SEXP for the SDF */
693
            ret = _create_sdf_sexp(iname2);
696
            ret = _create_sdf_sexp(iname2);
694
            return ret;
697
            return ret;
695
        } else { sqlite3_finalize(stmt); return R_NilValue; }
698
        } else { sqlite3_finalize(stmt); return R_NilValue; }
696
    } else if (row == R_NilValue || idxlen < 1) {
699
    } else if (row == R_NilValue || idxlen < 1) {
697
        sqlite3_finalize(stmt);
700
        sqlite3_finalize(stmt);
698
        return R_NilValue;
701
        return R_NilValue;
699
    } else if (IS_NUMERIC(row)) {
702
    } else if (IS_NUMERIC(row)) {
700
        sqlite3_finalize(stmt);
703
        sqlite3_finalize(stmt);
701
 
704
 
702
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
705
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
703
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
706
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
704
 
707
 
705
        /* append " limit ?,1" to the formed select statement */
708
        /* append " limit ?,1" to the formed select statement */
706
        _expand_buf(0, buflen+10);
709
        _expand_buf(0, buflen+10);
707
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
710
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
708
        /*Rprintf("sql [%d]: %s\n", buflen, g_sql_buf[0]); */
711
        /*Rprintf("sql [%d]: %s\n", buflen, g_sql_buf[0]); */
709
 
712
 
710
        index = ((int) REAL(row)[0]) - 1;
713
        index = ((int) REAL(row)[0]) - 1;
711
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
714
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
712
 
715
 
713
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
716
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
714
        if (_sqlite_error(res)) return R_NilValue;
717
        if (_sqlite_error(res)) return R_NilValue;
715
 
718
 
716
        sqlite3_bind_int(stmt, 1, index);
719
        sqlite3_bind_int(stmt, 1, index);
717
        res = sqlite3_step(stmt);
720
        res = sqlite3_step(stmt);
718
 
721
 
719
        /* create data frame */
722
        /* create data frame */
720
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
723
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
721
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
724
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
722
 
725
 
723
        /* put data in it */
726
        /* put data in it */
724
        if (index >= 0 && index < row_cnt) {
727
        if (index >= 0 && index < row_cnt) {
725
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
728
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
726
        }
729
        }
727
 
730
 
728
        for (i = 1; i < idxlen; i++) {
731
        for (i = 1; i < idxlen; i++) {
729
            sqlite3_reset(stmt);
732
            sqlite3_reset(stmt);
730
            index = ((int) REAL(row)[i]) - 1;
733
            index = ((int) REAL(row)[i]) - 1;
731
            if (index >= 0 && index < row_cnt) {
734
            if (index >= 0 && index < row_cnt) {
732
                sqlite3_bind_int(stmt, 1, index);
735
                sqlite3_bind_int(stmt, 1, index);
733
                res = sqlite3_step(stmt);
736
                res = sqlite3_step(stmt);
734
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
737
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
735
            }
738
            }
736
        }
739
        }
737
        sqlite3_finalize(stmt);
740
        sqlite3_finalize(stmt);
738
 
741
 
739
        /* shrink vectors */
742
        /* shrink vectors */
740
        if (row_index_len < idxlen) {
743
        if (row_index_len < idxlen) {
741
            for (i = 0; i < col_index_len; i++) {
744
            for (i = 0; i < col_index_len; i++) {
742
                SET_VECTOR_ELT(ret, i, 
745
                SET_VECTOR_ELT(ret, i, 
743
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
746
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
744
            }
747
            }
745
        }
748
        }
746
 
749
 
747
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
750
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
748
    } else if (IS_INTEGER(row)) {
751
    } else if (IS_INTEGER(row)) {
749
        /* same stuff as with IS_INTEGER, except for setting of var index*/
752
        /* same stuff as with IS_INTEGER, except for setting of var index*/
750
        sqlite3_finalize(stmt);
753
        sqlite3_finalize(stmt);
751
 
754
 
752
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
755
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
753
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
756
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
754
 
757
 
755
        /* append " limit ?,1" to the formed select statement */
758
        /* append " limit ?,1" to the formed select statement */
756
        _expand_buf(0, buflen+10);
759
        _expand_buf(0, buflen+10);
757
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
760
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
758
 
761
 
759
        index = INTEGER(row)[0] - 1;
762
        index = INTEGER(row)[0] - 1;
760
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
763
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
761
 
764
 
762
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
765
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
763
        if (_sqlite_error(res)) return R_NilValue;
766
        if (_sqlite_error(res)) return R_NilValue;
764
 
767
 
765
        sqlite3_bind_int(stmt, 1, index);
768
        sqlite3_bind_int(stmt, 1, index);
766
        res = sqlite3_step(stmt);
769
        res = sqlite3_step(stmt);
767
 
770
 
768
        /* create data frame */
771
        /* create data frame */
769
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
772
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
770
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
773
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
771
 
774
 
772
        /* put data in it */
775
        /* put data in it */
773
        if (index >= 0 && index < row_cnt) {
776
        if (index >= 0 && index < row_cnt) {
774
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
777
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
775
        }
778
        }
776
 
779
 
777
        for (i = 1; i < idxlen; i++) {
780
        for (i = 1; i < idxlen; i++) {
778
            sqlite3_reset(stmt);
781
            sqlite3_reset(stmt);
779
            index = INTEGER(row)[i] - 1;
782
            index = INTEGER(row)[i] - 1;
780
            if (index >= 0 && index < row_cnt) {
783
            if (index >= 0 && index < row_cnt) {
781
                sqlite3_bind_int(stmt, 1, index);
784
                sqlite3_bind_int(stmt, 1, index);
782
                res = sqlite3_step(stmt); 
785
                res = sqlite3_step(stmt); 
783
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
786
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
784
            }
787
            }
785
        }
788
        }
786
        sqlite3_finalize(stmt);
789
        sqlite3_finalize(stmt);
787
 
790
 
788
        /* shrink vectors */
791
        /* shrink vectors */
789
        if (row_index_len < idxlen) {
792
        if (row_index_len < idxlen) {
790
            for (i = 0; i < col_index_len; i++) {
793
            for (i = 0; i < col_index_len; i++) {
791
                SET_VECTOR_ELT(ret, i, 
794
                SET_VECTOR_ELT(ret, i, 
792
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
795
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
793
            }
796
            }
794
        }
797
        }
795
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
798
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
796
    } else if (IS_LOGICAL(row)) {
799
    } else if (IS_LOGICAL(row)) {
797
        /* */
800
        /* */
798
        sqlite3_finalize(stmt);
801
        sqlite3_finalize(stmt);
799
        int est_row_cnt = 0;
802
        int est_row_cnt = 0;
800
 
803
 
801
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
804
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
802
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
805
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
803
 
806
 
804
        /* append " limit ?,1" to the formed select statement */
807
        /* append " limit ?,1" to the formed select statement */
805
        _expand_buf(0, buflen+10);
808
        _expand_buf(0, buflen+10);
806
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
809
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
807
 
810
 
808
        /* find if there is any TRUE element in the vector */
811
        /* find if there is any TRUE element in the vector */
809
        for (i = 0; i < idxlen && i < row_cnt; i++) {
812
        for (i = 0; i < idxlen && i < row_cnt; i++) {
810
            if (LOGICAL(row)[i]) break;
813
            if (LOGICAL(row)[i]) break;
811
        }
814
        }
812
 
815
 
813
        if (i < idxlen && i < row_cnt) {
816
        if (i < idxlen && i < row_cnt) {
814
            est_row_cnt = (idxlen-i) * (row_cnt/idxlen);
817
            est_row_cnt = (idxlen-i) * (row_cnt/idxlen);
815
            if (row_cnt%idxlen > i) est_row_cnt += (row_cnt%idxlen - i);
818
            if (row_cnt%idxlen > i) est_row_cnt += (row_cnt%idxlen - i);
816
 
819
 
817
            res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
820
            res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
818
            if (_sqlite_error(res)) return R_NilValue;
821
            if (_sqlite_error(res)) return R_NilValue;
819
 
822
 
820
            sqlite3_bind_int(stmt, 1, i);
823
            sqlite3_bind_int(stmt, 1, i);
821
            sqlite3_step(stmt);
824
            sqlite3_step(stmt);
822
            ret = _setup_df_sexp1(stmt, iname, col_index_len, est_row_cnt, dup_indices);
825
            ret = _setup_df_sexp1(stmt, iname, col_index_len, est_row_cnt, dup_indices);
823
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
826
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
824
            
827
            
825
            for (i++ ; i < row_cnt; i++) {
828
            for (i++ ; i < row_cnt; i++) {
826
                if (LOGICAL(row)[i%idxlen]) {
829
                if (LOGICAL(row)[i%idxlen]) {
827
                    sqlite3_reset(stmt);
830
                    sqlite3_reset(stmt);
828
                    sqlite3_bind_int(stmt, 1, i);
831
                    sqlite3_bind_int(stmt, 1, i);
829
                    sqlite3_step(stmt);
832
                    sqlite3_step(stmt);
830
                    _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
833
                    _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
831
                }
834
                }
832
            }
835
            }
833
        }
836
        }
834
 
837
 
835
        sqlite3_finalize(stmt);
838
        sqlite3_finalize(stmt);
836
 
839
 
837
        /* shrink vectors */
840
        /* shrink vectors */
838
        if (est_row_cnt > 0 && row_index_len < est_row_cnt) {
841
        if (est_row_cnt > 0 && row_index_len < est_row_cnt) {
839
            for (i = 0; i < col_index_len; i++) {
842
            for (i = 0; i < col_index_len; i++) {
840
                SET_VECTOR_ELT(ret, i, 
843
                SET_VECTOR_ELT(ret, i, 
841
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
844
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
842
            }
845
            }
843
        }
846
        }
844
 
847
 
845
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
848
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
846
    }
849
    }
847
 
850
 
848
    UNUSE_SDF2(iname);
851
    UNUSE_SDF2(iname);
849
 
852
 
850
    if (ret != R_NilValue && col_index_len > 1) {
853
    if (ret != R_NilValue && col_index_len > 1) {
851
        SET_CLASS(ret, mkString("data.frame"));
854
        SET_CLASS(ret, mkString("data.frame"));
852
        _set_rownames2(ret);
855
        _set_rownames2(ret);
853
    } else if (ret != R_NilValue && col_index_len == 1) {
856
    } else if (ret != R_NilValue && col_index_len == 1) {
854
        ret = VECTOR_ELT(ret, 0);
857
        ret = VECTOR_ELT(ret, 0);
855
    }
858
    }
856
 
859
 
857
    return ret;
860
    return ret;
858
}
861
}
859
 
862
 
860
SEXP sdf_rbind(SEXP sdf, SEXP data) {
863
SEXP sdf_rbind(SEXP sdf, SEXP data) {
861
    char *class;
864
    char *class;
862
    char *iname = SDF_INAME(sdf), *colname, *rowname;
865
    char *iname = SDF_INAME(sdf), *colname;
863
    SEXP ret = R_NilValue, col, names, levels, rownames;
866
    SEXP ret = R_NilValue, col, names, levels, rownames;
864
    int ncols, buflen, buflen2, i, j, res, nrows, *types, rownames_type;
867
    int ncols, buflen, buflen2, i, j, res, nrows, *types, rownames_type;
865
    sqlite3_stmt *stmt;
868
    sqlite3_stmt *stmt;
866
    const char *type;
869
    const char *type;
867
    char *rn_str; int rn_int; double rn_dbl;
870
    char *rn_str; 
868
 
871
 
869
    class = CHAR_ELT(GET_CLASS(data), 0);
872
    class = CHAR_ELT(GET_CLASS(data), 0);
870
    if (strcmp(class,"data.frame") == 0) {
873
    if (strcmp(class,"data.frame") == 0) {
871
        /* check table names, types. variables may not be in same order, as
874
        /* check table names, types. variables may not be in same order, as
872
         * long as names and types are identical. */
875
         * long as names and types are identical. */
873
        names = GET_NAMES(data);
876
        names = GET_NAMES(data);
874
        ncols = GET_LENGTH(names);
877
        ncols = GET_LENGTH(names);
875
 
878
 
876
        buflen = sprintf(g_sql_buf[0], "select 1");
879
        buflen = sprintf(g_sql_buf[0], "select 1");
877
        for (i = 0; i < ncols; i++) {
880
        for (i = 0; i < ncols; i++) {
878
            _expand_buf(0, buflen + 100);
881
            _expand_buf(0, buflen + 100);
879
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
882
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
880
        }
883
        }
881
        _expand_buf(0, buflen + 100);
884
        _expand_buf(0, buflen + 100);
882
        sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
885
        sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
883
 
886
 
884
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
887
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
885
        if (res != SQLITE_OK) { /* column name mismatch */
888
        if (res != SQLITE_OK) { /* column name mismatch */
886
            _sqlite_error(res);
889
            _sqlite_error(res);
887
            Rprintf("Error: column names should exactly match the names of the SDF.\n");
890
            Rprintf("Error: column names should exactly match the names of the SDF.\n");
888
            return ret;
891
            return ret;
889
        }
892
        }
890
 
893
 
891
        /* now check the type */
894
        /* now check the type */
892
        types = (int *)R_alloc(ncols, sizeof(int));
895
        types = (int *)R_alloc(ncols, sizeof(int));
893
        for (i = 0; i< ncols; i++) {
896
        for (i = 0; i< ncols; i++) {
894
            type = sqlite3_column_decltype(stmt, i+1); /* +1 bec 1st col is "1" */
897
            type = sqlite3_column_decltype(stmt, i+1); /* +1 bec 1st col is "1" */
895
 
898
 
896
            col = VECTOR_ELT(data, i);
899
            col = VECTOR_ELT(data, i);
897
            /* class = CHAR_ELT(GET_CLASS(col),0); */
900
            /* class = CHAR_ELT(GET_CLASS(col),0); */
898
 
901
 
899
            if (strcmp(type, "double") == 0 && IS_NUMERIC(col)) types[i] = SQLITE_FLOAT;
902
            if (strcmp(type, "double") == 0 && IS_NUMERIC(col)) types[i] = SQLITE_FLOAT;
900
            else if (strcmp(type, "text") == 0 && IS_CHARACTER(col)) types[i] = SQLITE_TEXT;
903
            else if (strcmp(type, "text") == 0 && IS_CHARACTER(col)) types[i] = SQLITE_TEXT;
901
            else if (strcmp(type, "int") == 0) { 
904
            else if (strcmp(type, "int") == 0) { 
902
                types[i] = SQLITE_INTEGER;
905
                types[i] = SQLITE_INTEGER;
903
                if (isUnordered(col)) {  /* test if factor */
906
                if (isUnordered(col)) {  /* test if factor */
904
                    colname = CHAR_ELT(names, i);
907
                    colname = CHAR_ELT(names, i);
905
                    sqlite3_stmt *stmt2;
908
                    sqlite3_stmt *stmt2;
906
                    if (!_is_factor2(iname, "factor", colname)) break;
909
                    if (!_is_factor2(iname, "factor", colname)) break;
907
                    sprintf(g_sql_buf[1], "[%s].[factor %s]", iname, colname);
910
                    sprintf(g_sql_buf[1], "[%s].[factor %s]", iname, colname);
908
                    nrows = _get_row_count2(g_sql_buf[1], 0);
911
                    nrows = _get_row_count2(g_sql_buf[1], 0);
909
 
912
 
910
                    /* levels in sdf must be >= levels in df */
913
                    /* levels in sdf must be >= levels in df */
911
                    levels = GET_LEVELS(col);
914
                    levels = GET_LEVELS(col);
912
                    if (nrows < GET_LENGTH(levels)) {
915
                    if (nrows < GET_LENGTH(levels)) {
913
                        Rprintf("Error: The data frame variable %s has more levels than"
916
                        Rprintf("Error: The data frame variable %s has more levels than"
914
                                " its SDF counterpart.\n", colname);
917
                                " its SDF counterpart.\n", colname);
915
                        break;
918
                        break;
916
                    }
919
                    }
917
 
920
 
918
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
921
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
919
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
922
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
920
                    _sqlite_error(res);
923
                    _sqlite_error(res);
921
                    
924
                    
922
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
925
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
923
                        sqlite3_step(stmt2);
926
                        sqlite3_step(stmt2);
924
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
927
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
925
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
928
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
926
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
929
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
927
                                    CHAR_ELT(levels, j));
930
                                    CHAR_ELT(levels, j));
928
                            sqlite3_finalize(stmt2);
931
                            sqlite3_finalize(stmt2);
929
                            break;
932
                            break;
930
                        }
933
                        }
931
                    }
934
                    }
932
                    sqlite3_finalize(stmt2);
935
                    sqlite3_finalize(stmt2);
933
                } else if (isOrdered(col)) { /* same with ordered */
936
                } else if (isOrdered(col)) { /* same with ordered */
934
                    colname = CHAR_ELT(names, i);
937
                    colname = CHAR_ELT(names, i);
935
                    sqlite3_stmt *stmt2;
938
                    sqlite3_stmt *stmt2;
936
                    if (!_is_factor2(iname, "ordered", colname)) break;
939
                    if (!_is_factor2(iname, "ordered", colname)) break;
937
                    sprintf(g_sql_buf[1], "[%s].[ordered %s]", iname, colname);
940
                    sprintf(g_sql_buf[1], "[%s].[ordered %s]", iname, colname);
938
                    nrows = _get_row_count2(g_sql_buf[1], 0);
941
                    nrows = _get_row_count2(g_sql_buf[1], 0);
939
 
942
 
940
                    /* levels in sdf must be >= levels in df */
943
                    /* levels in sdf must be >= levels in df */
941
                    levels = GET_LEVELS(col);
944
                    levels = GET_LEVELS(col);
942
                    if (nrows < GET_LENGTH(levels)) {
945
                    if (nrows < GET_LENGTH(levels)) {
943
                        Rprintf("Error: The data frame variable %s has more levels than"
946
                        Rprintf("Error: The data frame variable %s has more levels than"
944
                                " its SDF counterpart.\n", colname);
947
                                " its SDF counterpart.\n", colname);
945
                        break;
948
                        break;
946
                    }
949
                    }
947
 
950
 
948
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
951
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
949
                    sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
952
                    sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
950
                    
953
                    
951
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
954
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
952
                        sqlite3_step(stmt2);
955
                        sqlite3_step(stmt2);
953
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
956
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
954
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
957
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
955
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
958
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
956
                                    CHAR_ELT(levels, j));
959
                                    CHAR_ELT(levels, j));
957
                            sqlite3_finalize(stmt2);
960
                            sqlite3_finalize(stmt2);
958
                            break;
961
                            break;
959
                        }
962
                        }
960
                    }
963
                    }
961
                    sqlite3_finalize(stmt2);
964
                    sqlite3_finalize(stmt2);
962
                }  /* else if class == "ordered" */
965
                }  /* else if class == "ordered" */
963
            } /* if integer */
966
            } /* if integer */
964
        } /* for loop for column type checking */
967
        } /* for loop for column type checking */
965
 
968
 
966
        sqlite3_finalize(stmt);
969
        sqlite3_finalize(stmt);
967
        if (i < ncols) {
970
        if (i < ncols) {
968
            Rprintf("Error: type mismatch at variable %s\n", CHAR_ELT(names, i));
971
            Rprintf("Error: type mismatch at variable %s\n", CHAR_ELT(names, i));
969
            return ret;
972
            return ret;
970
        }
973
        }
971
 
974
 
972
        /* create the insert statement */
975
        /* create the insert statement */
973
        buflen = sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name]", iname);
976
        buflen = sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name]", iname);
974
        buflen2 = sprintf(g_sql_buf[1], "values(?");
977
        buflen2 = sprintf(g_sql_buf[1], "values(?");
975
        for (i = 0; i < ncols; i++) {
978
        for (i = 0; i < ncols; i++) {
976
            _expand_buf(0, buflen+100);
979
            _expand_buf(0, buflen+100);
977
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
980
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
978
            _expand_buf(1, buflen2+5);
981
            _expand_buf(1, buflen2+5);
979
            buflen2 += sprintf(g_sql_buf[1]+buflen2, ",?");
982
            buflen2 += sprintf(g_sql_buf[1]+buflen2, ",?");
980
        }
983
        }
981
 
984
 
982
        _expand_buf(2, buflen + buflen2 + 10);
985
        _expand_buf(2, buflen + buflen2 + 10);
983
        sprintf(g_sql_buf[2], "%s) %s)", g_sql_buf[0], g_sql_buf[1]);
986
        sprintf(g_sql_buf[2], "%s) %s)", g_sql_buf[0], g_sql_buf[1]);
984
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
987
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
985
        if (_sqlite_error(res)) return ret;
988
        if (_sqlite_error(res)) return ret;
986
 
989
 
987
        /* finally, add rows */
990
        /* finally, add rows */
988
        rownames = getAttrib(data, R_RowNamesSymbol); /* GET_ROWNAMES(data); */
991
        rownames = getAttrib(data, R_RowNamesSymbol); /* GET_ROWNAMES(data); */
989
        nrows = LENGTH(rownames);
992
        nrows = LENGTH(rownames);
990
        rownames_type = TYPEOF(rownames);
993
        rownames_type = TYPEOF(rownames);
991
 
994
 
992
        _sqlite_begin;
995
        _sqlite_begin;
993
        for (i = 0; i < nrows; i++) {
996
        for (i = 0; i < nrows; i++) {
994
            sqlite3_reset(stmt);
997
            sqlite3_reset(stmt);
995
            if (rownames_type == STRSXP) {
998
            if (rownames_type == STRSXP) {
996
                rn_str = CHAR_ELT(rownames, i);
999
                rn_str = CHAR_ELT(rownames, i);
997
            } else if (rownames_type == INTSXP) {
1000
            } else if (rownames_type == INTSXP) {
998
                sprintf(g_sql_buf[1], "%d", INTEGER(rownames)[i]);
1001
                sprintf(g_sql_buf[1], "%d", INTEGER(rownames)[i]);
999
                rn_str = g_sql_buf[1];
1002
                rn_str = g_sql_buf[1];
1000
            } else if (rownames_type == REALSXP) {
1003
            } else if (rownames_type == REALSXP) {
1001
                sprintf(g_sql_buf[1], "%f", REAL(rownames)[i]);
1004
                sprintf(g_sql_buf[1], "%f", REAL(rownames)[i]);
1002
                rn_str = g_sql_buf[1];
1005
                rn_str = g_sql_buf[1];
1003
            } else {
1006
            } else {
1004
                sprintf(g_sql_buf[1], "%d", i);
1007
                sprintf(g_sql_buf[1], "%d", i);
1005
                rn_str = g_sql_buf[1];
1008
                rn_str = g_sql_buf[1];
1006
            }
1009
            }
1007
            sqlite3_bind_text(stmt, 1, rn_str, -1, SQLITE_STATIC);
1010
            sqlite3_bind_text(stmt, 1, rn_str, -1, SQLITE_STATIC);
1008
 
1011
 
1009
            for (j = 0; j < ncols; j++) {
1012
            for (j = 0; j < ncols; j++) {
1010
                col = VECTOR_ELT(data, j);
1013
                col = VECTOR_ELT(data, j);
1011
                switch(types[j]) {
1014
                switch(types[j]) {
1012
                    case SQLITE_FLOAT:
1015
                    case SQLITE_FLOAT:
1013
                        sqlite3_bind_double(stmt, j+2, REAL(col)[i]); break;
1016
                        sqlite3_bind_double(stmt, j+2, REAL(col)[i]); break;
1014
                    case SQLITE_TEXT:
1017
                    case SQLITE_TEXT:
1015
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(col, i), -1, SQLITE_STATIC); break;
1018
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(col, i), -1, SQLITE_STATIC); break;
1016
                    case SQLITE_INTEGER:
1019
                    case SQLITE_INTEGER:
1017
                    default:  /* runtime error if we're wrong */
1020
                    default:  /* runtime error if we're wrong */
1018
                        sqlite3_bind_int(stmt, j+2, INTEGER(col)[i]); break;
1021
                        sqlite3_bind_int(stmt, j+2, INTEGER(col)[i]); break;
1019
                }
1022
                }
1020
            }
1023
            }
1021
 
1024
 
1022
            res = sqlite3_step(stmt);
1025
            res = sqlite3_step(stmt);
1023
            if (res != SQLITE_DONE) { /* row name pk conflict */
1026
            if (res != SQLITE_DONE) { /* row name pk conflict */
1024
                for (j = 1; res != SQLITE_DONE; j++) { /* _normally_, j shouldn't overflow */
1027
                for (j = 1; res != SQLITE_DONE; j++) { /* _normally_, j shouldn't overflow */
1025
                    sqlite3_reset(stmt);
1028
                    sqlite3_reset(stmt);
1026
                    sprintf(g_sql_buf[2], "%s-%d", rn_str, j);
1029
                    sprintf(g_sql_buf[2], "%s-%d", rn_str, j);
1027
                    sqlite3_bind_text(stmt, 1, g_sql_buf[2], -1, SQLITE_STATIC);
1030
                    sqlite3_bind_text(stmt, 1, g_sql_buf[2], -1, SQLITE_STATIC);
1028
                    res = sqlite3_step(stmt);
1031
                    res = sqlite3_step(stmt);
1029
                }
1032
                }
1030
            } 
1033
            } 
1031
        }
1034
        }
1032
 
1035
 
1033
        sqlite3_finalize(stmt);
1036
        sqlite3_finalize(stmt);
1034
        _sqlite_commit;
1037
        _sqlite_commit;
1035
        ret = sdf;
1038
        ret = sdf;
1036
    } else if (strcmp(class,"sqlite.data.frame") == 0) {
1039
    } else if (strcmp(class,"sqlite.data.frame") == 0) {
1037
    }
1040
    }
1038
 
1041
 
1039
    return ret;
1042
    return ret;
1040
}
1043
}
1041
 
1044
 
1042
 
1045
 
1043
SEXP sdf_get_iname(SEXP sdf) {
1046
SEXP sdf_get_iname(SEXP sdf) {
-
 
1047
    char *iname, *sql;
-
 
1048
    sqlite3_stmt *stmt;
-
 
1049
    SEXP ret, names;
-
 
1050
 
-
 
1051
    iname = SDF_INAME(sdf);
-
 
1052
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
-
 
1053
 
-
 
1054
    sql = "select internal_name, rel_filename from workspace where internal_name=?";
-
 
1055
    sqlite3_prepare(g_workspace, sql, -1, &stmt, NULL);
-
 
1056
    sqlite3_bind_text(stmt, 1, iname, -1, SQLITE_STATIC);
-
 
1057
    sqlite3_step(stmt);
-
 
1058
 
-
 
1059
    PROTECT(ret = NEW_CHARACTER(2));
-
 
1060
    SET_STRING_ELT(ret, 0, mkChar((char *)sqlite3_column_text(stmt, 0)));
-
 
1061
    SET_STRING_ELT(ret, 1, mkChar((char *)sqlite3_column_text(stmt, 1)));
-
 
1062
 
-
 
1063
    PROTECT(names = NEW_CHARACTER(2));
-
 
1064
    SET_STRING_ELT(names, 0, mkChar("Internal Name"));
-
 
1065
    SET_STRING_ELT(names, 1, mkChar("File"));
-
 
1066
 
1044
    return _getListElement(sdf, "iname");
1067
    SET_NAMES(ret, names);
-
 
1068
 
-
 
1069
    sqlite3_finalize(stmt);
-
 
1070
    UNPROTECT(2);
-
 
1071
 
-
 
1072
    return ret;
1045
}
1073
}