sqliteds.pas 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. procedure InternalCloseHandle; override;
  42. procedure BuildLinkedList; override;
  43. protected
  44. procedure RetrieveFieldDefs; override;
  45. function GetRowsAffected:Integer; override;
  46. public
  47. procedure ExecuteDirect(const ASQL: String); override;
  48. function QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects: Boolean): String; override;
  49. function ReturnString: String; override;
  50. class function SqliteVersion: String; override;
  51. property SqliteEncoding: String read GetSqliteEncoding;
  52. end;
  53. implementation
  54. uses
  55. sqlite, db, strutils;
  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, DataSize: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. DataSize := 0;
  116. ColumnStr := UpperCase(String(ColumnNames[i + ColumnCount]));
  117. if (ColumnStr = 'INTEGER') or (ColumnStr = 'INT') then
  118. begin
  119. if AutoIncrementKey and
  120. (UpperCase(String(ColumnNames[i])) = UpperCase(PrimaryKey)) then
  121. begin
  122. AType := ftAutoInc;
  123. FAutoIncFieldNo := i;
  124. end
  125. else
  126. AType := ftInteger;
  127. end else if Pos('VARCHAR', ColumnStr) = 1 then
  128. begin
  129. AType := ftString;
  130. DataSize := StrToIntDef(Trim(ExtractDelimited(2, ColumnStr, ['(', ')'])), DefaultStringSize);
  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. FieldDefs.Add(String(ColumnNames[i]), AType, DataSize);
  168. //Set the pchar2sql function
  169. if AType in [ftString, ftMemo] then
  170. FGetSqlStr[i] := @Char2SQLStr
  171. else
  172. FGetSqlStr[i] := @Num2SQLStr;
  173. end;
  174. sqlite_finalize(vm, nil);
  175. {
  176. if FReturnCode <> SQLITE_ABORT then
  177. DatabaseError(ReturnString,Self);
  178. }
  179. end;
  180. function TSqliteDataset.GetRowsAffected: Integer;
  181. begin
  182. Result := sqlite_changes(FSqliteHandle);
  183. //Result := sqlite_last_statement_changes(FSqliteHandle);
  184. end;
  185. procedure TSqliteDataset.ExecuteDirect(const ASQL: String);
  186. var
  187. vm: Pointer;
  188. ColumnNames, ColumnValues: PPChar;
  189. ColCount: Integer;
  190. begin
  191. FReturnCode := sqlite_compile(FSqliteHandle, Pchar(ASQL), nil, @vm, nil);
  192. if FReturnCode <> SQLITE_OK then
  193. DatabaseError(ReturnString,Self);
  194. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  195. sqlite_finalize(vm, nil);
  196. end;
  197. procedure TSqliteDataset.BuildLinkedList;
  198. var
  199. TempItem: PDataRecord;
  200. vm: Pointer;
  201. ColumnNames, ColumnValues: PPChar;
  202. Counter, ColumnCount: Integer;
  203. begin
  204. //Get AutoInc Field initial value
  205. if FAutoIncFieldNo <> -1 then
  206. sqlite_exec(FSqliteHandle, PChar('Select Max(' + Fields[FAutoIncFieldNo].FieldName + ') from ' + FTableName),
  207. @GetAutoIncValue, @FNextAutoInc, nil);
  208. FReturnCode := sqlite_compile(FSqliteHandle, PChar(FSQL), nil, @vm, nil);
  209. if FReturnCode <> SQLITE_OK then
  210. DatabaseError(ReturnString, Self);
  211. FDataAllocated := True;
  212. TempItem := FBeginItem;
  213. FRecordCount := 0;
  214. FReturnCode := sqlite_step(vm, @ColumnCount, @ColumnValues, @ColumnNames);
  215. FRowCount := ColumnCount;
  216. //add extra rows for calculated fields
  217. if FCalcFieldList <> nil then
  218. Inc(FRowCount, FCalcFieldList.Count);
  219. FRowBufferSize := (SizeOf(PPChar) * FRowCount);
  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 ColumnCount - 1 do
  228. TempItem^.Row[Counter] := StrNew(ColumnValues[Counter]);
  229. //initialize calculated fields with nil
  230. for Counter := ColumnCount to FRowCount - 1 do
  231. TempItem^.Row[Counter] := nil;
  232. FReturnCode := sqlite_step(vm, @FRowCount, @ColumnValues, @ColumnNames);
  233. end;
  234. sqlite_finalize(vm, nil);
  235. // Attach EndItem
  236. TempItem^.Next := FEndItem;
  237. FEndItem^.Previous := TempItem;
  238. // Alloc item used in append/insert
  239. GetMem(FCacheItem^.Row, FRowBufferSize);
  240. for Counter := 0 to FRowCount - 1 do
  241. FCacheItem^.Row[Counter] := nil;
  242. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  243. GetMem(FBeginItem^.Row, FRowBufferSize);
  244. for Counter := 0 to FRowCount - 1 do
  245. FBeginItem^.Row[Counter] := nil;
  246. end;
  247. function TSqliteDataset.ReturnString: String;
  248. begin
  249. case FReturnCode of
  250. SQLITE_OK : Result := 'SQLITE_OK';
  251. SQLITE_ERROR : Result := 'SQLITE_ERROR';
  252. SQLITE_INTERNAL : Result := 'SQLITE_INTERNAL';
  253. SQLITE_PERM : Result := 'SQLITE_PERM';
  254. SQLITE_ABORT : Result := 'SQLITE_ABORT';
  255. SQLITE_BUSY : Result := 'SQLITE_BUSY';
  256. SQLITE_LOCKED : Result := 'SQLITE_LOCKED';
  257. SQLITE_NOMEM : Result := 'SQLITE_NOMEM';
  258. SQLITE_READONLY : Result := 'SQLITE_READONLY';
  259. SQLITE_INTERRUPT : Result := 'SQLITE_INTERRUPT';
  260. SQLITE_IOERR : Result := 'SQLITE_IOERR';
  261. SQLITE_CORRUPT : Result := 'SQLITE_CORRUPT';
  262. SQLITE_NOTFOUND : Result := 'SQLITE_NOTFOUND';
  263. SQLITE_FULL : Result := 'SQLITE_FULL';
  264. SQLITE_CANTOPEN : Result := 'SQLITE_CANTOPEN';
  265. SQLITE_PROTOCOL : Result := 'SQLITE_PROTOCOL';
  266. SQLITE_EMPTY : Result := 'SQLITE_EMPTY';
  267. SQLITE_SCHEMA : Result := 'SQLITE_SCHEMA';
  268. SQLITE_TOOBIG : Result := 'SQLITE_TOOBIG';
  269. SQLITE_CONSTRAINT : Result := 'SQLITE_CONSTRAINT';
  270. SQLITE_MISMATCH : Result := 'SQLITE_MISMATCH';
  271. SQLITE_MISUSE : Result := 'SQLITE_MISUSE';
  272. SQLITE_NOLFS : Result := 'SQLITE_NOLFS';
  273. SQLITE_AUTH : Result := 'SQLITE_AUTH';
  274. SQLITE_FORMAT : Result := 'SQLITE_FORMAT';
  275. SQLITE_RANGE : Result := 'SQLITE_RANGE';
  276. SQLITE_ROW :
  277. begin
  278. Result := 'SQLITE_ROW - not an error';
  279. Exit;
  280. end;
  281. SQLITE_DONE :
  282. begin
  283. Result := 'SQLITE_DONE - not an error';
  284. Exit;
  285. end;
  286. else
  287. Result := 'Unknow Return Value';
  288. end;
  289. Result := Result + ' - ' + sqlite_error_string(FReturnCode);
  290. end;
  291. function TSqliteDataset.GetSqliteEncoding: String;
  292. begin
  293. Result := String(sqlite_encoding);
  294. end;
  295. class function TSqliteDataset.SqliteVersion: String;
  296. begin
  297. Result := String(sqlite_version);
  298. end;
  299. function TSqliteDataset.QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects: Boolean): String;
  300. var
  301. vm: Pointer;
  302. ColumnNames, ColumnValues: PPChar;
  303. ColCount: Integer;
  304. procedure FillStrings;
  305. begin
  306. while FReturnCode = SQLITE_ROW do
  307. begin
  308. AStrList.Add(String(ColumnValues[0]));
  309. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  310. end;
  311. end;
  312. procedure FillStringsAndObjects;
  313. begin
  314. while FReturnCode = SQLITE_ROW do
  315. begin
  316. // I know, this code is really dirty!!
  317. AStrList.AddObject(String(ColumnValues[0]),
  318. TObject(PtrInt(StrToInt(String(ColumnValues[1])))));
  319. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  320. end;
  321. end;
  322. begin
  323. if FSqliteHandle = nil then
  324. GetSqliteHandle;
  325. Result := '';
  326. FReturnCode := sqlite_compile(FSqliteHandle, PChar(ASQL), nil, @vm, nil);
  327. if FReturnCode <> SQLITE_OK then
  328. DatabaseError(ReturnString,Self);
  329. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  330. if (FReturnCode = SQLITE_ROW) and (ColCount > 0) then
  331. begin
  332. Result := String(ColumnValues[0]);
  333. if AStrList <> nil then
  334. begin
  335. if FillObjects and (ColCount > 1) then
  336. FillStringsAndObjects
  337. else
  338. FillStrings;
  339. end;
  340. end;
  341. sqlite_finalize(vm, nil);
  342. end;
  343. end.