sqliteds.pas 12 KB

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