sqliteds.pas 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. unit sqliteds;
  2. {
  3. This is TSqliteDataset, 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. { TSqliteDataset }
  36. TSqliteDataset = class (TCustomSqliteDataset)
  37. private
  38. function SqliteExec(ASql:PChar; ACallback: TSqliteCdeclCallback; Data: Pointer):Integer;override;
  39. function InternalGetHandle: Pointer; override;
  40. function GetSqliteEncoding: String;
  41. function GetSqliteVersion: String; override;
  42. procedure InternalCloseHandle;override;
  43. procedure BuildLinkedList; override;
  44. protected
  45. procedure InternalInitFieldDefs; override;
  46. function GetRowsAffected:Integer; override;
  47. public
  48. procedure ExecuteDirect(const ASql: String);override;
  49. function ReturnString: String; override;
  50. function QuickQuery(const ASql:String;const AStrList: TStrings;FillObjects:Boolean):String;override;
  51. property SqliteEncoding: String read GetSqliteEncoding;
  52. end;
  53. implementation
  54. uses
  55. sqlite,db;
  56. //function sqlite_last_statement_changes(dbhandle:Pointer):longint;cdecl;external 'sqlite' name 'sqlite_last_statement_changes';
  57. function GetAutoIncValue(NextValue: Pointer; Columns: Integer; ColumnValues: PPChar; ColumnNames: PPChar): integer; cdecl;
  58. var
  59. CodeError, TempInt: Integer;
  60. begin
  61. TempInt:=-1;
  62. if ColumnValues[0] <> nil then
  63. begin
  64. Val(StrPas(ColumnValues[0]),TempInt,CodeError);
  65. if CodeError <> 0 then
  66. DatabaseError('SqliteDs - Error trying to get last autoinc value');
  67. end;
  68. Integer(NextValue^):=Succ(TempInt);
  69. Result:=1;
  70. end;
  71. { TSqliteDataset }
  72. function TSqliteDataset.SqliteExec(ASql: PChar; ACallback: TSqliteCdeclCallback; Data: Pointer): Integer;
  73. begin
  74. Result:=sqlite_exec(FSqliteHandle, ASql, ACallback, Data, nil);
  75. end;
  76. procedure TSqliteDataset.InternalCloseHandle;
  77. begin
  78. sqlite_close(FSqliteHandle);
  79. FSqliteHandle:=nil;
  80. end;
  81. function TSqliteDataset.InternalGetHandle: Pointer;
  82. begin
  83. Result:=sqlite_open(PChar(FFileName),0,nil);
  84. end;
  85. procedure TSqliteDataset.InternalInitFieldDefs;
  86. var
  87. ColumnCount,i:Integer;
  88. FieldSize:Word;
  89. AType:TFieldType;
  90. vm:Pointer;
  91. ColumnNames,ColumnValues:PPChar;
  92. ColumnStr:String;
  93. begin
  94. FieldDefs.Clear;
  95. FAutoIncFieldNo:=-1;
  96. sqlite_compile(FSqliteHandle,PChar(FSql),nil,@vm,nil);
  97. sqlite_step(vm,@ColumnCount,@ColumnValues,@ColumnNames);
  98. //Prepare the array of pchar2sql functions
  99. SetLength(FGetSqlStr,ColumnCount);
  100. //Set BufferSize
  101. FRowBufferSize:=(SizeOf(PPChar)*ColumnCount);
  102. // Sqlite is typeless (allows any type in any field)
  103. // regardless of what is in Create Table, but returns
  104. // exactly what is in Create Table statement
  105. // here is a trick to get the datatype.
  106. // If the field contains another type, may have problems
  107. for i:= 0 to ColumnCount - 1 do
  108. begin
  109. ColumnStr:= UpperCase(StrPas(ColumnNames[i + ColumnCount]));
  110. if (ColumnStr = 'INTEGER') or (ColumnStr = 'INT') then
  111. begin
  112. if AutoIncrementKey and
  113. (UpperCase(StrPas(ColumnNames[i])) = UpperCase(PrimaryKey)) then
  114. begin
  115. AType:= ftAutoInc;
  116. FAutoIncFieldNo:=i;
  117. end
  118. else
  119. AType:= ftInteger;
  120. FieldSize:=SizeOf(LongInt);
  121. end else if Pos('VARCHAR',ColumnStr) = 1 then
  122. begin
  123. AType:= ftString;
  124. FieldSize:=0;
  125. end else if Pos('BOOL',ColumnStr) = 1 then
  126. begin
  127. AType:= ftBoolean;
  128. FieldSize:=SizeOf(WordBool);
  129. end else if Pos('AUTOINC',ColumnStr) = 1 then
  130. begin
  131. AType:= ftAutoInc;
  132. FieldSize:=SizeOf(LongInt);
  133. if FAutoIncFieldNo = -1 then
  134. FAutoIncFieldNo:= i;
  135. end else if (Pos('FLOAT',ColumnStr)=1) or (Pos('NUMERIC',ColumnStr)=1) then
  136. begin
  137. AType:= ftFloat;
  138. FieldSize:=SizeOf(Double);
  139. end else if (ColumnStr = 'DATETIME') then
  140. begin
  141. AType:= ftDateTime;
  142. FieldSize:=SizeOf(TDateTime);
  143. end else if (ColumnStr = 'DATE') then
  144. begin
  145. AType:= ftDate;
  146. FieldSize:=SizeOf(TDateTime);
  147. end else if (ColumnStr = 'TIME') then
  148. begin
  149. AType:= ftTime;
  150. FieldSize:=SizeOf(TDateTime);
  151. end else if (ColumnStr = 'LARGEINT') then
  152. begin
  153. AType:= ftLargeInt;
  154. FieldSize:=SizeOf(LargeInt);
  155. end else if (ColumnStr = 'TEXT') then
  156. begin
  157. AType:= ftMemo;
  158. FieldSize:=0;
  159. end else if (ColumnStr = 'CURRENCY') then
  160. begin
  161. AType:= ftCurrency;
  162. FieldSize:=SizeOf(Double);
  163. end else if (ColumnStr = 'WORD') then
  164. begin
  165. AType:= ftWord;
  166. FieldSize:=SizeOf(Word);
  167. end else
  168. begin
  169. AType:=ftString;
  170. FieldSize:=0;
  171. end;
  172. FieldDefs.Add(StrPas(ColumnNames[i]), AType, FieldSize, False);
  173. //Set the pchar2sql function
  174. if AType in [ftString,ftMemo] then
  175. FGetSqlStr[i]:=@Char2SqlStr
  176. else
  177. FGetSqlStr[i]:=@Num2SqlStr;
  178. end;
  179. sqlite_finalize(vm, nil);
  180. {
  181. if FReturnCode <> SQLITE_ABORT then
  182. DatabaseError(ReturnString,Self);
  183. }
  184. end;
  185. function TSqliteDataset.GetRowsAffected: Integer;
  186. begin
  187. Result:=sqlite_changes(FSqliteHandle);
  188. //Result:=sqlite_last_statement_changes(FSqliteHandle);
  189. end;
  190. procedure TSqliteDataset.ExecuteDirect(const ASql: String);
  191. var
  192. vm:Pointer;
  193. ColumnNames,ColumnValues:PPChar;
  194. ColCount:Integer;
  195. begin
  196. FReturnCode:=sqlite_compile(FSqliteHandle,Pchar(ASql),nil,@vm,nil);
  197. if FReturnCode <> SQLITE_OK then
  198. DatabaseError(ReturnString,Self);
  199. FReturnCode:=sqlite_step(vm,@ColCount,@ColumnValues,@ColumnNames);
  200. sqlite_finalize(vm, nil);
  201. end;
  202. procedure TSqliteDataset.BuildLinkedList;
  203. var
  204. TempItem:PDataRecord;
  205. vm:Pointer;
  206. ColumnNames,ColumnValues:PPChar;
  207. Counter:Integer;
  208. begin
  209. //Get AutoInc Field initial value
  210. if FAutoIncFieldNo <> -1 then
  211. sqlite_exec(FSqliteHandle,PChar('Select Max('+Fields[FAutoIncFieldNo].FieldName+') from ' + FTableName),
  212. @GetAutoIncValue,@FNextAutoInc,nil);
  213. FReturnCode:=sqlite_compile(FSqliteHandle,Pchar(FSql),nil,@vm,nil);
  214. if FReturnCode <> SQLITE_OK then
  215. DatabaseError(ReturnString,Self);
  216. FDataAllocated:=True;
  217. TempItem:=FBeginItem;
  218. FRecordCount:=0;
  219. FReturnCode:=sqlite_step(vm,@FRowCount,@ColumnValues,@ColumnNames);
  220. while FReturnCode = SQLITE_ROW do
  221. begin
  222. Inc(FRecordCount);
  223. New(TempItem^.Next);
  224. TempItem^.Next^.Previous:=TempItem;
  225. TempItem:=TempItem^.Next;
  226. GetMem(TempItem^.Row,FRowBufferSize);
  227. for Counter := 0 to FRowCount - 1 do
  228. TempItem^.Row[Counter]:=StrNew(ColumnValues[Counter]);
  229. FReturnCode:=sqlite_step(vm,@FRowCount,@ColumnValues,@ColumnNames);
  230. end;
  231. sqlite_finalize(vm, nil);
  232. // Attach EndItem
  233. TempItem^.Next:=FEndItem;
  234. FEndItem^.Previous:=TempItem;
  235. // Alloc item used in append/insert
  236. GetMem(FCacheItem^.Row,FRowBufferSize);
  237. for Counter := 0 to FRowCount - 1 do
  238. FCacheItem^.Row[Counter]:=nil;
  239. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  240. GetMem(FBeginItem^.Row,FRowBufferSize);
  241. for Counter := 0 to FRowCount - 1 do
  242. FBeginItem^.Row[Counter]:=nil;
  243. end;
  244. function TSqliteDataset.ReturnString: String;
  245. begin
  246. case FReturnCode of
  247. SQLITE_OK : Result := 'SQLITE_OK';
  248. SQLITE_ERROR : Result := 'SQLITE_ERROR';
  249. SQLITE_INTERNAL : Result := 'SQLITE_INTERNAL';
  250. SQLITE_PERM : Result := 'SQLITE_PERM';
  251. SQLITE_ABORT : Result := 'SQLITE_ABORT';
  252. SQLITE_BUSY : Result := 'SQLITE_BUSY';
  253. SQLITE_LOCKED : Result := 'SQLITE_LOCKED';
  254. SQLITE_NOMEM : Result := 'SQLITE_NOMEM';
  255. SQLITE_READONLY : Result := 'SQLITE_READONLY';
  256. SQLITE_INTERRUPT : Result := 'SQLITE_INTERRUPT';
  257. SQLITE_IOERR : Result := 'SQLITE_IOERR';
  258. SQLITE_CORRUPT : Result := 'SQLITE_CORRUPT';
  259. SQLITE_NOTFOUND : Result := 'SQLITE_NOTFOUND';
  260. SQLITE_FULL : Result := 'SQLITE_FULL';
  261. SQLITE_CANTOPEN : Result := 'SQLITE_CANTOPEN';
  262. SQLITE_PROTOCOL : Result := 'SQLITE_PROTOCOL';
  263. SQLITE_EMPTY : Result := 'SQLITE_EMPTY';
  264. SQLITE_SCHEMA : Result := 'SQLITE_SCHEMA';
  265. SQLITE_TOOBIG : Result := 'SQLITE_TOOBIG';
  266. SQLITE_CONSTRAINT : Result := 'SQLITE_CONSTRAINT';
  267. SQLITE_MISMATCH : Result := 'SQLITE_MISMATCH';
  268. SQLITE_MISUSE : Result := 'SQLITE_MISUSE';
  269. SQLITE_NOLFS : Result := 'SQLITE_NOLFS';
  270. SQLITE_AUTH : Result := 'SQLITE_AUTH';
  271. SQLITE_FORMAT : Result := 'SQLITE_FORMAT';
  272. SQLITE_RANGE : Result := 'SQLITE_RANGE';
  273. SQLITE_ROW : begin Result := 'SQLITE_ROW - not an error'; Exit; end;
  274. SQLITE_DONE : begin Result := 'SQLITE_DONE - not an error'; Exit; end;
  275. else
  276. Result:='Unknow Return Value';
  277. end;
  278. Result:=Result+' - '+sqlite_error_string(FReturnCode);
  279. end;
  280. function TSqliteDataset.GetSqliteEncoding: String;
  281. begin
  282. Result:=StrPas(sqlite_encoding);
  283. end;
  284. function TSqliteDataset.GetSqliteVersion: String;
  285. begin
  286. Result:=StrPas(sqlite_version);
  287. end;
  288. function TSqliteDataset.QuickQuery(const ASql:String;const AStrList: TStrings;FillObjects:Boolean):String;
  289. var
  290. vm:Pointer;
  291. ColumnNames,ColumnValues:PPChar;
  292. ColCount:Integer;
  293. procedure FillStrings;
  294. begin
  295. while FReturnCode = SQLITE_ROW do
  296. begin
  297. AStrList.Add(StrPas(ColumnValues[0]));
  298. FReturnCode:=sqlite_step(vm,@ColCount,@ColumnValues,@ColumnNames);
  299. end;
  300. end;
  301. procedure FillStringsAndObjects;
  302. begin
  303. while FReturnCode = SQLITE_ROW do
  304. begin
  305. // I know, this code is really dirty!!
  306. AStrList.AddObject(StrPas(ColumnValues[0]),TObject(PtrInt(StrToInt(StrPas(ColumnValues[1])))));
  307. FReturnCode:=sqlite_step(vm,@ColCount,@ColumnValues,@ColumnNames);
  308. end;
  309. end;
  310. begin
  311. if FSqliteHandle = nil then
  312. GetSqliteHandle;
  313. Result:='';
  314. FReturnCode:=sqlite_compile(FSqliteHandle,Pchar(ASql),nil,@vm,nil);
  315. if FReturnCode <> SQLITE_OK then
  316. DatabaseError(ReturnString,Self);
  317. FReturnCode:=sqlite_step(vm,@ColCount,@ColumnValues,@ColumnNames);
  318. if (FReturnCode = SQLITE_ROW) and (ColCount > 0) then
  319. begin
  320. Result:=StrPas(ColumnValues[0]);
  321. if AStrList <> nil then
  322. begin
  323. if FillObjects and (ColCount > 1) then
  324. FillStringsAndObjects
  325. else
  326. FillStrings;
  327. end;
  328. end;
  329. sqlite_finalize(vm, nil);
  330. end;
  331. end.