sqlite3ds.pas 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. var
  136. vm:Pointer;
  137. ColumnStr:String;
  138. i,ColumnCount:Integer;
  139. AType:TFieldType;
  140. begin
  141. {$ifdef DEBUG}
  142. WriteLn('##TSqlite3Dataset.InternalInitFieldDefs##');
  143. {$endif}
  144. FAutoIncFieldNo:=-1;
  145. FieldDefs.Clear;
  146. FReturnCode := sqlite3_prepare(FSqliteHandle, PChar(FSql), -1, @vm, nil);
  147. if FReturnCode <> SQLITE_OK then
  148. DatabaseError(ReturnString, Self);
  149. sqlite3_step(vm);
  150. ColumnCount:=sqlite3_column_count(vm);
  151. //Set BufferSize
  152. FRowBufferSize:=(SizeOf(PPChar)*ColumnCount);
  153. //Prepare the array of pchar2sql functions
  154. SetLength(FGetSqlStr,ColumnCount);
  155. for i := 0 to ColumnCount - 1 do
  156. begin
  157. ColumnStr := UpperCase(String(sqlite3_column_decltype(vm,i)));
  158. if (ColumnStr = 'INTEGER') or (ColumnStr = 'INT') then
  159. begin
  160. if AutoIncrementKey and (UpperCase(String(sqlite3_column_name(vm,i))) = UpperCase(PrimaryKey)) then
  161. begin
  162. AType := ftAutoInc;
  163. FAutoIncFieldNo := i;
  164. end
  165. else
  166. AType := ftInteger;
  167. end else if Pos('VARCHAR',ColumnStr) = 1 then
  168. begin
  169. AType := ftString;
  170. end else if Pos('BOOL',ColumnStr) = 1 then
  171. begin
  172. AType := ftBoolean;
  173. end else if Pos('AUTOINC',ColumnStr) = 1 then
  174. begin
  175. AType := ftAutoInc;
  176. if FAutoIncFieldNo = -1 then
  177. FAutoIncFieldNo := i;
  178. end else if (Pos('FLOAT',ColumnStr)=1) or (Pos('NUMERIC',ColumnStr)=1) then
  179. begin
  180. AType := ftFloat;
  181. end else if (ColumnStr = 'DATETIME') then
  182. begin
  183. AType := ftDateTime;
  184. end else if (ColumnStr = 'DATE') then
  185. begin
  186. AType := ftDate;
  187. end else if (ColumnStr = 'LARGEINT') then
  188. begin
  189. AType := ftLargeInt;
  190. end else if (ColumnStr = 'TIME') then
  191. begin
  192. AType := ftTime;
  193. end else if (ColumnStr = 'TEXT') then
  194. begin
  195. AType := ftMemo;
  196. end else if (ColumnStr = 'CURRENCY') then
  197. begin
  198. AType := ftCurrency;
  199. end else if (ColumnStr = 'WORD') then
  200. begin
  201. AType := ftWord;
  202. end else
  203. begin
  204. AType := ftString;
  205. end;
  206. if AType = ftString then
  207. FieldDefs.Add(String(sqlite3_column_name(vm,i)), AType, dsMaxStringSize)
  208. else
  209. FieldDefs.Add(String(sqlite3_column_name(vm,i)), AType);
  210. //Set the pchar2sql function
  211. if AType in [ftString,ftMemo] then
  212. FGetSqlStr[i]:=@Char2SqlStr
  213. else
  214. FGetSqlStr[i]:=@Num2SqlStr;
  215. {$ifdef DEBUG}
  216. writeln(' Field[',i,'] Name: ',sqlite3_column_name(vm,i));
  217. writeln(' Field[',i,'] Type: ',sqlite3_column_decltype(vm,i));
  218. {$endif}
  219. end;
  220. sqlite3_finalize(vm);
  221. {$ifdef DEBUG}
  222. writeln(' FieldDefs.Count: ',FieldDefs.Count);
  223. {$endif}
  224. end;
  225. function TSqlite3Dataset.GetRowsAffected: Integer;
  226. begin
  227. Result:=sqlite3_changes(FSqliteHandle);
  228. end;
  229. procedure TSqlite3Dataset.ExecuteDirect(const ASql: String);
  230. var
  231. vm:Pointer;
  232. begin
  233. FReturnCode:=sqlite3_prepare(FSqliteHandle,Pchar(ASql),-1,@vm,nil);
  234. if FReturnCode <> SQLITE_OK then
  235. DatabaseError(ReturnString,Self);
  236. FReturnCode:=sqlite3_step(vm);
  237. sqlite3_finalize(vm);
  238. end;
  239. procedure TSqlite3Dataset.BuildLinkedList;
  240. var
  241. TempItem:PDataRecord;
  242. vm:Pointer;
  243. Counter:Integer;
  244. begin
  245. //Get AutoInc Field initial value
  246. if FAutoIncFieldNo <> -1 then
  247. sqlite3_exec(FSqliteHandle,PChar('Select Max('+Fields[FAutoIncFieldNo].FieldName+') from ' + FTableName),
  248. @GetAutoIncValue,@FNextAutoInc,nil);
  249. FReturnCode:=sqlite3_prepare(FSqliteHandle,Pchar(FSql),-1,@vm,nil);
  250. if FReturnCode <> SQLITE_OK then
  251. DatabaseError(ReturnString,Self);
  252. FDataAllocated:=True;
  253. TempItem:=FBeginItem;
  254. FRecordCount:=0;
  255. FRowCount:=sqlite3_column_count(vm);
  256. FReturnCode:=sqlite3_step(vm);
  257. while FReturnCode = SQLITE_ROW do
  258. begin
  259. Inc(FRecordCount);
  260. New(TempItem^.Next);
  261. TempItem^.Next^.Previous:=TempItem;
  262. TempItem:=TempItem^.Next;
  263. GetMem(TempItem^.Row,FRowBufferSize);
  264. for Counter := 0 to FRowCount - 1 do
  265. TempItem^.Row[Counter]:=StrNew(sqlite3_column_text(vm,Counter));
  266. FReturnCode:=sqlite3_step(vm);
  267. end;
  268. sqlite3_finalize(vm);
  269. // Attach EndItem
  270. TempItem^.Next:=FEndItem;
  271. FEndItem^.Previous:=TempItem;
  272. // Alloc temporary item used in append/insert
  273. GetMem(FCacheItem^.Row,FRowBufferSize);
  274. for Counter := 0 to FRowCount - 1 do
  275. FCacheItem^.Row[Counter]:=nil;
  276. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  277. GetMem(FBeginItem^.Row,FRowBufferSize);
  278. //Todo: see if is better to nullif using FillDWord
  279. for Counter := 0 to FRowCount - 1 do
  280. FBeginItem^.Row[Counter]:=nil;
  281. end;
  282. function TSqlite3Dataset.ReturnString: String;
  283. begin
  284. Result := SqliteCode2Str(FReturnCode) + ' - ' + sqlite3_errmsg(FSqliteHandle);
  285. end;
  286. function TSqlite3Dataset.GetSqliteVersion: String;
  287. begin
  288. Result := String(sqlite3_version());
  289. end;
  290. function TSqlite3Dataset.QuickQuery(const ASql:String;const AStrList: TStrings;FillObjects:Boolean):String;
  291. var
  292. vm:Pointer;
  293. procedure FillStrings;
  294. begin
  295. while FReturnCode = SQLITE_ROW do
  296. begin
  297. AStrList.Add(String(sqlite3_column_text(vm,0)));
  298. FReturnCode := sqlite3_step(vm);
  299. end;
  300. end;
  301. procedure FillStringsAndObjects;
  302. begin
  303. while FReturnCode = SQLITE_ROW do
  304. begin
  305. AStrList.AddObject(String(sqlite3_column_text(vm,0)), TObject(PtrInt(sqlite3_column_int(vm,1))));
  306. FReturnCode := sqlite3_step(vm);
  307. end;
  308. end;
  309. begin
  310. if FSqliteHandle = nil then
  311. GetSqliteHandle;
  312. Result := '';
  313. FReturnCode := sqlite3_prepare(FSqliteHandle,Pchar(ASql), -1, @vm, nil);
  314. if FReturnCode <> SQLITE_OK then
  315. DatabaseError(ReturnString,Self);
  316. FReturnCode := sqlite3_step(vm);
  317. if (FReturnCode = SQLITE_ROW) and (sqlite3_column_count(vm) > 0) then
  318. begin
  319. Result := String(sqlite3_column_text(vm,0));
  320. if AStrList <> nil then
  321. begin
  322. if FillObjects and (sqlite3_column_count(vm) > 1) then
  323. FillStringsAndObjects
  324. else
  325. FillStrings;
  326. end;
  327. end;
  328. sqlite3_finalize(vm);
  329. end;
  330. end.