Skip to content

Commit 8c9eb2e

Browse files
committed
* inst/@octave_sqlite/sqlwrite.m: add auto table create
1 parent 2249b6e commit 8c9eb2e

File tree

1 file changed

+59
-11
lines changed

1 file changed

+59
-11
lines changed

inst/@octave_sqlite/sqlwrite.m

Lines changed: 59 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -143,17 +143,24 @@ function sqlwrite (db, tablename, data, varargin)
143143
# create table if ne need to ?
144144
s = fetch(db, sprintf("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';", tablename));
145145
if isempty(s)
146-
# TODO need to create the table
147-
# if we have ColumnType property in, use it for the types
148-
%{
149-
values = "";
150-
for col=1:numel(cols)
151-
coldata = subsref (data, substruct("{}", {':', col}))
152-
class(coldata)
153-
iscellstr(coldata)
154-
class(coldata(1))
155-
endfor
156-
%}
146+
if isempty(coltypes)
147+
coltypes = {};
148+
# currently assign all columns to numeric if not specified as it will
149+
# handle all types of data
150+
for col=1:numel(cols)
151+
coltypes{end+1} = "numeric";
152+
endfor
153+
endif
154+
tsql = sprintf("CREATE TABLE %s (", tablename);
155+
for idx=1:numel(coltypes)
156+
if idx > 1
157+
tsql = [tsql ", "];
158+
endif
159+
tsql = [tsql sprintf("%s %s", cols{idx}, coltypes{idx})];
160+
endfor
161+
tsql = [tsql ")"];
162+
163+
execute(db, tsql);
157164
endif
158165

159166
execute(db, sql);
@@ -181,3 +188,44 @@ function sqlwrite (db, tablename, data, varargin)
181188
%! delete(testfile);
182189
%! endif
183190
%! end_unwind_protect
191+
192+
%!test
193+
%! testfile = tempname;
194+
%! t = dbtable([1;2],['Name1';'Name2'], 'VariableNames', {'Id','Name'});
195+
%! unwind_protect
196+
%! db = sqlite(testfile, "create");
197+
%! sqlwrite(db, "Test", t, 'ColumnType', {'numeric', 'text'});
198+
%! data = sqlread(db, 'Test');
199+
%! assert(size(data), [2 2]);
200+
%!
201+
%! sqlwrite(db, "Test", t);
202+
%! data = sqlread(db, 'Test');
203+
%! assert(size(data), [4 2]);
204+
%!
205+
%! close(db);
206+
%!
207+
%! unwind_protect_cleanup
208+
%! db = 0;
209+
%!
210+
%! if exist(testfile, "file")
211+
%! delete(testfile);
212+
%! endif
213+
%! end_unwind_protect
214+
215+
%!test
216+
%! testfile = tempname;
217+
%! t = dbtable([1;2],['Name1';'Name2'], 'VariableNames', {'Id','Name'});
218+
%! unwind_protect
219+
%! db = sqlite(testfile, "create");
220+
%! sqlwrite(db, "Test", t);
221+
%! data = sqlread(db, 'Test');
222+
%! assert(size(data), [2 2]);
223+
%! close(db);
224+
%!
225+
%! unwind_protect_cleanup
226+
%! db = 0;
227+
%!
228+
%! if exist(testfile, "file")
229+
%! delete(testfile);
230+
%! endif
231+
%! end_unwind_protect

0 commit comments

Comments
 (0)