sqliteds.pas 12 KB

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