sqlite3ds.pas 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. unit sqlite3ds;
  2. {
  3. This is TSqlite3Dataset, a TDataset descendant class for use with fpc compiler
  4. Copyright (C) 2004 Luiz Américo Pereira Câmara
  5. Email: [email protected]
  6. This library is free software; you can redistribute it and/or modify it
  7. under the terms of the GNU Library General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or (at your
  9. option) any later version with the following modification:
  10. As a special exception, the copyright holders of this library give you
  11. permission to link this library with independent modules to produce an
  12. executable, regardless of the license terms of these independent modules,and
  13. to copy and distribute the resulting executable under terms of your choice,
  14. provided that you also meet, for each linked independent module, the terms
  15. and conditions of the license of that module. An independent module is a
  16. module which is not derived from or based on this library. If you modify
  17. this library, you may extend this exception to your version of the library,
  18. but you are not obligated to do so. If you do not wish to do so, delete this
  19. exception statement from your version.
  20. This program is distributed in the hope that it will be useful, but WITHOUT
  21. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  22. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
  23. for more details.
  24. You should have received a copy of the GNU Library General Public License
  25. along with this library; if not, write to the Free Software Foundation,
  26. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  27. }
  28. {$mode objfpc}
  29. {$H+}
  30. { $Define DEBUG}
  31. interface
  32. uses
  33. Classes, SysUtils, customsqliteds;
  34. type
  35. { TSqlite3Dataset }
  36. TSqlite3Dataset = class (TCustomSqliteDataset)
  37. private
  38. function SqliteExec(ASql:PChar; ACallback: TSqliteCdeclCallback; Data: Pointer):Integer;override;
  39. function InternalGetHandle: Pointer; override;
  40. function GetSqliteVersion: String; override;
  41. procedure InternalCloseHandle;override;
  42. procedure BuildLinkedList; override;
  43. protected
  44. procedure InternalInitFieldDefs; override;
  45. function GetRowsAffected:Integer; override;
  46. public
  47. procedure ExecuteDirect(const ASql: String);override;
  48. function ReturnString: String; override;
  49. function QuickQuery(const ASql:String;const AStrList: TStrings;FillObjects:Boolean):String;override;
  50. end;
  51. implementation
  52. uses
  53. sqlite3,db;
  54. function SqliteCode2Str(Code: Integer): String;
  55. begin
  56. case Code of
  57. SQLITE_OK : Result := 'SQLITE_OK';
  58. SQLITE_ERROR : Result := 'SQLITE_ERROR';
  59. SQLITE_INTERNAL : Result := 'SQLITE_INTERNAL';
  60. SQLITE_PERM : Result := 'SQLITE_PERM';
  61. SQLITE_ABORT : Result := 'SQLITE_ABORT';
  62. SQLITE_BUSY : Result := 'SQLITE_BUSY';
  63. SQLITE_LOCKED : Result := 'SQLITE_LOCKED';
  64. SQLITE_NOMEM : Result := 'SQLITE_NOMEM';
  65. SQLITE_READONLY : Result := 'SQLITE_READONLY';
  66. SQLITE_INTERRUPT : Result := 'SQLITE_INTERRUPT';
  67. SQLITE_IOERR : Result := 'SQLITE_IOERR';
  68. SQLITE_CORRUPT : Result := 'SQLITE_CORRUPT';
  69. SQLITE_NOTFOUND : Result := 'SQLITE_NOTFOUND';
  70. SQLITE_FULL : Result := 'SQLITE_FULL';
  71. SQLITE_CANTOPEN : Result := 'SQLITE_CANTOPEN';
  72. SQLITE_PROTOCOL : Result := 'SQLITE_PROTOCOL';
  73. SQLITE_EMPTY : Result := 'SQLITE_EMPTY';
  74. SQLITE_SCHEMA : Result := 'SQLITE_SCHEMA';
  75. SQLITE_TOOBIG : Result := 'SQLITE_TOOBIG';
  76. SQLITE_CONSTRAINT : Result := 'SQLITE_CONSTRAINT';
  77. SQLITE_MISMATCH : Result := 'SQLITE_MISMATCH';
  78. SQLITE_MISUSE : Result := 'SQLITE_MISUSE';
  79. SQLITE_NOLFS : Result := 'SQLITE_NOLFS';
  80. SQLITE_AUTH : Result := 'SQLITE_AUTH';
  81. SQLITE_FORMAT : Result := 'SQLITE_FORMAT';
  82. SQLITE_RANGE : Result := 'SQLITE_RANGE';
  83. SQLITE_ROW : Result := 'SQLITE_ROW';
  84. SQLITE_NOTADB : Result := 'SQLITE_NOTADB';
  85. SQLITE_DONE : Result := 'SQLITE_DONE';
  86. else
  87. Result:='Unknown Return Value';
  88. end;
  89. end;
  90. function GetAutoIncValue(NextValue: Pointer; Columns: Integer; ColumnValues: PPChar; ColumnNames: PPChar): integer; cdecl;
  91. var
  92. CodeError, TempInt: Integer;
  93. begin
  94. TempInt := -1;
  95. if ColumnValues[0] <> nil then
  96. begin
  97. Val(String(ColumnValues[0]), TempInt, CodeError);
  98. if CodeError <> 0 then
  99. DatabaseError('TSqlite3Dataset: Error trying to get last autoinc value');
  100. end;
  101. Integer(NextValue^) := Succ(TempInt);
  102. Result := 1;
  103. end;
  104. { TSqlite3Dataset }
  105. function TSqlite3Dataset.SqliteExec(ASql: PChar; ACallback: TSqliteCdeclCallback; Data: Pointer): Integer;
  106. begin
  107. Result:=sqlite3_exec(FSqliteHandle, ASql, ACallback, Data, nil);
  108. end;
  109. procedure TSqlite3Dataset.InternalCloseHandle;
  110. begin
  111. sqlite3_close(FSqliteHandle);
  112. FSqliteHandle:=nil;
  113. //todo:handle return data
  114. end;
  115. function TSqlite3Dataset.InternalGetHandle: Pointer;
  116. const
  117. CheckFileSql = 'Select Name from sqlite_master LIMIT 1';
  118. var
  119. vm: Pointer;
  120. ErrorStr: String;
  121. begin
  122. sqlite3_open(PChar(FFileName), @Result);
  123. //sqlite3_open returns SQLITE_OK even for invalid files
  124. //do additional check here
  125. FReturnCode := sqlite3_prepare(Result, CheckFileSql, -1, @vm, nil);
  126. if FReturnCode <> SQLITE_OK then
  127. begin
  128. ErrorStr := SqliteCode2Str(FReturnCode) + ' - ' + sqlite3_errmsg(Result);;
  129. sqlite3_close(Result);
  130. DatabaseError(ErrorStr, Self);
  131. end;
  132. sqlite3_finalize(vm);
  133. end;
  134. procedure TSqlite3Dataset.InternalInitFieldDefs;
  135. const
  136. FieldSizeMap: array[Boolean] of Integer = (0, dsMaxStringSize);
  137. var
  138. vm: Pointer;
  139. ColumnStr: String;
  140. i, ColumnCount: Integer;
  141. AType: TFieldType;
  142. begin
  143. {$ifdef DEBUG}
  144. WriteLn('##TSqlite3Dataset.InternalInitFieldDefs##');
  145. {$endif}
  146. FAutoIncFieldNo := -1;
  147. FieldDefs.Clear;
  148. FReturnCode := sqlite3_prepare(FSqliteHandle, PChar(FSql), -1, @vm, nil);
  149. if FReturnCode <> SQLITE_OK then
  150. DatabaseError(ReturnString, Self);
  151. sqlite3_step(vm);
  152. ColumnCount := sqlite3_column_count(vm);
  153. //Set BufferSize
  154. FRowBufferSize := (SizeOf(PPChar) * ColumnCount);
  155. //Prepare the array of pchar2sql functions
  156. SetLength(FGetSqlStr, ColumnCount);
  157. for i := 0 to ColumnCount - 1 do
  158. begin
  159. ColumnStr := UpperCase(String(sqlite3_column_decltype(vm, i)));
  160. if (ColumnStr = 'INTEGER') or (ColumnStr = 'INT') then
  161. begin
  162. if AutoIncrementKey and (UpperCase(String(sqlite3_column_name(vm, i))) = UpperCase(PrimaryKey)) then
  163. begin
  164. AType := ftAutoInc;
  165. FAutoIncFieldNo := i;
  166. end
  167. else
  168. AType := ftInteger;
  169. end else if Pos('VARCHAR', ColumnStr) = 1 then
  170. begin
  171. AType := ftString;
  172. end else if Pos('BOOL', ColumnStr) = 1 then
  173. begin
  174. AType := ftBoolean;
  175. end else if Pos('AUTOINC', ColumnStr) = 1 then
  176. begin
  177. AType := ftAutoInc;
  178. if FAutoIncFieldNo = -1 then
  179. FAutoIncFieldNo := i;
  180. end else if (Pos('FLOAT', ColumnStr) = 1) or (Pos('NUMERIC', ColumnStr) = 1) then
  181. begin
  182. AType := ftFloat;
  183. end else if (ColumnStr = 'DATETIME') then
  184. begin
  185. AType := ftDateTime;
  186. end else if (ColumnStr = 'DATE') then
  187. begin
  188. AType := ftDate;
  189. end else if (ColumnStr = 'LARGEINT') then
  190. begin
  191. AType := ftLargeInt;
  192. end else if (ColumnStr = 'TIME') then
  193. begin
  194. AType := ftTime;
  195. end else if (ColumnStr = 'TEXT') then
  196. begin
  197. AType := ftMemo;
  198. end else if (ColumnStr = 'CURRENCY') then
  199. begin
  200. AType := ftCurrency;
  201. end else if (ColumnStr = 'WORD') then
  202. begin
  203. AType := ftWord;
  204. end else if (ColumnStr = '') then
  205. begin
  206. case sqlite3_column_type(vm, i) of
  207. SQLITE_INTEGER:
  208. AType := ftInteger;
  209. SQLITE_FLOAT:
  210. AType := ftFloat;
  211. else
  212. AType := ftString;
  213. end;
  214. end else
  215. begin
  216. AType := ftString;
  217. end;
  218. FieldDefs.Add(String(sqlite3_column_name(vm, i)), AType, FieldSizeMap[AType = ftString]);
  219. //Set the pchar2sql function
  220. if AType in [ftString, ftMemo] then
  221. FGetSqlStr[i] := @Char2SqlStr
  222. else
  223. FGetSqlStr[i] := @Num2SqlStr;
  224. {$ifdef DEBUG}
  225. writeln(' Field[',i,'] Name: ', sqlite3_column_name(vm,i));
  226. writeln(' Field[',i,'] Type: ', sqlite3_column_decltype(vm,i));
  227. {$endif}
  228. end;
  229. sqlite3_finalize(vm);
  230. {$ifdef DEBUG}
  231. writeln(' FieldDefs.Count: ', FieldDefs.Count);
  232. {$endif}
  233. end;
  234. function TSqlite3Dataset.GetRowsAffected: Integer;
  235. begin
  236. Result:=sqlite3_changes(FSqliteHandle);
  237. end;
  238. procedure TSqlite3Dataset.ExecuteDirect(const ASql: String);
  239. var
  240. vm:Pointer;
  241. begin
  242. FReturnCode:=sqlite3_prepare(FSqliteHandle,Pchar(ASql),-1,@vm,nil);
  243. if FReturnCode <> SQLITE_OK then
  244. DatabaseError(ReturnString,Self);
  245. FReturnCode:=sqlite3_step(vm);
  246. sqlite3_finalize(vm);
  247. end;
  248. procedure TSqlite3Dataset.BuildLinkedList;
  249. var
  250. TempItem:PDataRecord;
  251. vm:Pointer;
  252. Counter:Integer;
  253. begin
  254. //Get AutoInc Field initial value
  255. if FAutoIncFieldNo <> -1 then
  256. sqlite3_exec(FSqliteHandle,PChar('Select Max('+Fields[FAutoIncFieldNo].FieldName+') from ' + FTableName),
  257. @GetAutoIncValue,@FNextAutoInc,nil);
  258. FReturnCode:=sqlite3_prepare(FSqliteHandle,Pchar(FSql),-1,@vm,nil);
  259. if FReturnCode <> SQLITE_OK then
  260. DatabaseError(ReturnString,Self);
  261. FDataAllocated:=True;
  262. TempItem:=FBeginItem;
  263. FRecordCount:=0;
  264. FRowCount:=sqlite3_column_count(vm);
  265. FReturnCode:=sqlite3_step(vm);
  266. while FReturnCode = SQLITE_ROW do
  267. begin
  268. Inc(FRecordCount);
  269. New(TempItem^.Next);
  270. TempItem^.Next^.Previous:=TempItem;
  271. TempItem:=TempItem^.Next;
  272. GetMem(TempItem^.Row,FRowBufferSize);
  273. for Counter := 0 to FRowCount - 1 do
  274. TempItem^.Row[Counter]:=StrNew(sqlite3_column_text(vm,Counter));
  275. FReturnCode:=sqlite3_step(vm);
  276. end;
  277. sqlite3_finalize(vm);
  278. // Attach EndItem
  279. TempItem^.Next:=FEndItem;
  280. FEndItem^.Previous:=TempItem;
  281. // Alloc temporary item used in append/insert
  282. GetMem(FCacheItem^.Row,FRowBufferSize);
  283. for Counter := 0 to FRowCount - 1 do
  284. FCacheItem^.Row[Counter]:=nil;
  285. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  286. GetMem(FBeginItem^.Row,FRowBufferSize);
  287. //Todo: see if is better to nullif using FillDWord
  288. for Counter := 0 to FRowCount - 1 do
  289. FBeginItem^.Row[Counter]:=nil;
  290. end;
  291. function TSqlite3Dataset.ReturnString: String;
  292. begin
  293. Result := SqliteCode2Str(FReturnCode) + ' - ' + sqlite3_errmsg(FSqliteHandle);
  294. end;
  295. function TSqlite3Dataset.GetSqliteVersion: String;
  296. begin
  297. Result := String(sqlite3_version());
  298. end;
  299. function TSqlite3Dataset.QuickQuery(const ASql:String;const AStrList: TStrings;FillObjects:Boolean):String;
  300. var
  301. vm:Pointer;
  302. procedure FillStrings;
  303. begin
  304. while FReturnCode = SQLITE_ROW do
  305. begin
  306. AStrList.Add(String(sqlite3_column_text(vm,0)));
  307. FReturnCode := sqlite3_step(vm);
  308. end;
  309. end;
  310. procedure FillStringsAndObjects;
  311. begin
  312. while FReturnCode = SQLITE_ROW do
  313. begin
  314. AStrList.AddObject(String(sqlite3_column_text(vm,0)), TObject(PtrInt(sqlite3_column_int(vm,1))));
  315. FReturnCode := sqlite3_step(vm);
  316. end;
  317. end;
  318. begin
  319. if FSqliteHandle = nil then
  320. GetSqliteHandle;
  321. Result := '';
  322. FReturnCode := sqlite3_prepare(FSqliteHandle,Pchar(ASql), -1, @vm, nil);
  323. if FReturnCode <> SQLITE_OK then
  324. DatabaseError(ReturnString,Self);
  325. FReturnCode := sqlite3_step(vm);
  326. if (FReturnCode = SQLITE_ROW) and (sqlite3_column_count(vm) > 0) then
  327. begin
  328. Result := String(sqlite3_column_text(vm,0));
  329. if AStrList <> nil then
  330. begin
  331. if FillObjects and (sqlite3_column_count(vm) > 1) then
  332. FillStringsAndObjects
  333. else
  334. FillStrings;
  335. end;
  336. end;
  337. sqlite3_finalize(vm);
  338. end;
  339. end.