The R Project SVN R-packages

Rev

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

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