sqliteds.pas 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 GetSqliteEncoding: String;
  39. protected
  40. procedure BuildLinkedList; override;
  41. function GetLastInsertRowId: Int64; override;
  42. function GetRowsAffected:Integer; override;
  43. function InternalGetHandle: Pointer; override;
  44. procedure InternalCloseHandle; override;
  45. procedure RetrieveFieldDefs; override;
  46. function SqliteExec(ASQL: PAnsiChar; ACallback: TSqliteCdeclCallback; Data: Pointer): Integer; override;
  47. public
  48. procedure ExecuteDirect(const ASQL: String); override;
  49. function QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects: Boolean): String; override;
  50. function ReturnString: String; override;
  51. class function SqliteVersion: String; override;
  52. property SqliteEncoding: String read GetSqliteEncoding;
  53. end;
  54. implementation
  55. uses
  56. sqlite, db, strutils;
  57. //function sqlite_last_statement_changes(dbhandle:Pointer):longint;cdecl;external 'sqlite' name 'sqlite_last_statement_changes';
  58. function GetAutoIncValue(NextValue: Pointer; Columns: Integer; ColumnValues: PPAnsiChar; ColumnNames: PPAnsiChar): Integer; cdecl;
  59. var
  60. CodeError, TempInt: Integer;
  61. begin
  62. TempInt := 0;
  63. if ColumnValues[0] <> nil then
  64. begin
  65. Val(String(ColumnValues[0]), TempInt, CodeError);
  66. if CodeError <> 0 then
  67. DatabaseError('TSqliteDataset: Error trying to get last autoinc value');
  68. end;
  69. Integer(NextValue^) := Succ(TempInt);
  70. Result := 1;
  71. end;
  72. { TSqliteDataset }
  73. function TSqliteDataset.SqliteExec(ASQL: PAnsiChar; ACallback: TSqliteCdeclCallback; Data: Pointer): Integer;
  74. begin
  75. Result := sqlite_exec(FSqliteHandle, ASQL, ACallback, Data, nil);
  76. end;
  77. procedure TSqliteDataset.InternalCloseHandle;
  78. begin
  79. sqlite_close(FSqliteHandle);
  80. FSqliteHandle := nil;
  81. end;
  82. function TSqliteDataset.InternalGetHandle: Pointer;
  83. var
  84. ErrorStr: PAnsiChar;
  85. begin
  86. Result := sqlite_open(PAnsiChar(FFileName), 0, @ErrorStr);
  87. if Result = nil then
  88. begin
  89. DatabaseError('Error opening "' + FFileName + '": ' + String(ErrorStr));
  90. sqlite_freemem(ErrorStr);
  91. end;
  92. end;
  93. procedure TSqliteDataset.RetrieveFieldDefs;
  94. var
  95. ColumnCount, i, DataSize:Integer;
  96. AType: TFieldType;
  97. vm: Pointer;
  98. ColumnNames, ColumnValues:PPAnsiChar;
  99. ColumnStr: String;
  100. begin
  101. FieldDefs.Clear;
  102. FAutoIncFieldNo := -1;
  103. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(FEffectiveSQL), nil, @vm, nil);
  104. if FReturnCode <> SQLITE_OK then
  105. DatabaseError(ReturnString, Self);
  106. sqlite_step(vm, @ColumnCount, @ColumnValues, @ColumnNames);
  107. //Prepare the array of pchar2sql functions
  108. SetLength(FGetSqlStr, ColumnCount);
  109. // Sqlite is typeless (allows any type in any field)
  110. // regardless of what is in Create Table, but returns
  111. // exactly what is in Create Table statement
  112. // here is a trick to get the datatype.
  113. // If the field contains another type, may have problems
  114. for i := 0 to ColumnCount - 1 do
  115. begin
  116. DataSize := 0;
  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. DataSize := StrToIntDef(Trim(ExtractDelimited(2, ColumnStr, ['(', ')'])), DefaultStringSize);
  132. end else if Pos('BOOL', ColumnStr) = 1 then
  133. begin
  134. AType := ftBoolean;
  135. end else if Pos('AUTOINC', ColumnStr) = 1 then
  136. begin
  137. AType := ftAutoInc;
  138. if FAutoIncFieldNo = -1 then
  139. FAutoIncFieldNo := i;
  140. end else if (Pos('FLOAT', ColumnStr)=1) or (Pos('NUMERIC', ColumnStr) = 1) then
  141. begin
  142. AType := ftFloat;
  143. end else if (ColumnStr = 'DATETIME') then
  144. begin
  145. AType := ftDateTime;
  146. end else if (ColumnStr = 'DATE') then
  147. begin
  148. AType := ftDate;
  149. end else if (ColumnStr = 'TIME') then
  150. begin
  151. AType := ftTime;
  152. end else if (ColumnStr = 'LARGEINT') or (ColumnStr = 'BIGINT') then
  153. begin
  154. AType := ftLargeInt;
  155. end else if (ColumnStr = 'TEXT') then
  156. begin
  157. AType := ftMemo;
  158. end else if (ColumnStr = 'CURRENCY') then
  159. begin
  160. AType := ftCurrency;
  161. end else if (ColumnStr = 'WORD') then
  162. begin
  163. AType := ftWord;
  164. end else
  165. begin
  166. AType := ftString;
  167. end;
  168. FieldDefs.Add(FieldDefs.MakeNameUnique(String(ColumnNames[i])), AType, DataSize);
  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: PPAnsiChar;
  190. ColCount: Integer;
  191. begin
  192. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(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: PPAnsiChar;
  203. Counter, ColumnCount: Integer;
  204. begin
  205. //Get AutoInc Field initial value
  206. if FAutoIncFieldNo <> -1 then
  207. sqlite_exec(FSqliteHandle, PAnsiChar('Select Max(' + FieldDefs[FAutoIncFieldNo].Name + ') from ' + FTableName),
  208. @GetAutoIncValue, @FNextAutoInc, nil);
  209. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(FEffectiveSQL), 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(PPAnsiChar) * 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(FSavedEditItem^.Row, FRowBufferSize);
  241. for Counter := 0 to FRowCount - 1 do
  242. FSavedEditItem^.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.GetLastInsertRowId: Int64;
  249. begin
  250. Result := sqlite_last_insert_rowid(FSqliteHandle);
  251. end;
  252. function TSqliteDataset.ReturnString: String;
  253. begin
  254. case FReturnCode of
  255. SQLITE_OK : Result := 'SQLITE_OK';
  256. SQLITE_ERROR : Result := 'SQLITE_ERROR';
  257. SQLITE_INTERNAL : Result := 'SQLITE_INTERNAL';
  258. SQLITE_PERM : Result := 'SQLITE_PERM';
  259. SQLITE_ABORT : Result := 'SQLITE_ABORT';
  260. SQLITE_BUSY : Result := 'SQLITE_BUSY';
  261. SQLITE_LOCKED : Result := 'SQLITE_LOCKED';
  262. SQLITE_NOMEM : Result := 'SQLITE_NOMEM';
  263. SQLITE_READONLY : Result := 'SQLITE_READONLY';
  264. SQLITE_INTERRUPT : Result := 'SQLITE_INTERRUPT';
  265. SQLITE_IOERR : Result := 'SQLITE_IOERR';
  266. SQLITE_CORRUPT : Result := 'SQLITE_CORRUPT';
  267. SQLITE_NOTFOUND : Result := 'SQLITE_NOTFOUND';
  268. SQLITE_FULL : Result := 'SQLITE_FULL';
  269. SQLITE_CANTOPEN : Result := 'SQLITE_CANTOPEN';
  270. SQLITE_PROTOCOL : Result := 'SQLITE_PROTOCOL';
  271. SQLITE_EMPTY : Result := 'SQLITE_EMPTY';
  272. SQLITE_SCHEMA : Result := 'SQLITE_SCHEMA';
  273. SQLITE_TOOBIG : Result := 'SQLITE_TOOBIG';
  274. SQLITE_CONSTRAINT : Result := 'SQLITE_CONSTRAINT';
  275. SQLITE_MISMATCH : Result := 'SQLITE_MISMATCH';
  276. SQLITE_MISUSE : Result := 'SQLITE_MISUSE';
  277. SQLITE_NOLFS : Result := 'SQLITE_NOLFS';
  278. SQLITE_AUTH : Result := 'SQLITE_AUTH';
  279. SQLITE_FORMAT : Result := 'SQLITE_FORMAT';
  280. SQLITE_RANGE : Result := 'SQLITE_RANGE';
  281. SQLITE_ROW :
  282. begin
  283. Result := 'SQLITE_ROW - not an error';
  284. Exit;
  285. end;
  286. SQLITE_DONE :
  287. begin
  288. Result := 'SQLITE_DONE - not an error';
  289. Exit;
  290. end;
  291. else
  292. Result := 'Unknow Return Value';
  293. end;
  294. Result := Result + ' - ' + sqlite_error_string(FReturnCode);
  295. end;
  296. function TSqliteDataset.GetSqliteEncoding: String;
  297. begin
  298. Result := String(sqlite_encoding);
  299. end;
  300. class function TSqliteDataset.SqliteVersion: String;
  301. begin
  302. Result := String(sqlite_version);
  303. end;
  304. function TSqliteDataset.QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects: Boolean): String;
  305. var
  306. vm: Pointer;
  307. ColumnNames, ColumnValues: PPAnsiChar;
  308. ColCount: Integer;
  309. procedure FillStrings;
  310. begin
  311. while FReturnCode = SQLITE_ROW do
  312. begin
  313. AStrList.Add(String(ColumnValues[0]));
  314. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  315. end;
  316. end;
  317. procedure FillStringsAndObjects;
  318. begin
  319. while FReturnCode = SQLITE_ROW do
  320. begin
  321. // I know, this code is really dirty!!
  322. AStrList.AddObject(String(ColumnValues[0]),
  323. TObject(PtrInt(StrToInt(String(ColumnValues[1])))));
  324. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  325. end;
  326. end;
  327. begin
  328. if FSqliteHandle = nil then
  329. GetSqliteHandle;
  330. Result := '';
  331. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(ASQL), nil, @vm, nil);
  332. if FReturnCode <> SQLITE_OK then
  333. DatabaseError(ReturnString,Self);
  334. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  335. if (FReturnCode = SQLITE_ROW) and (ColCount > 0) then
  336. begin
  337. Result := String(ColumnValues[0]);
  338. if AStrList <> nil then
  339. begin
  340. if FillObjects and (ColCount > 1) then
  341. FillStringsAndObjects
  342. else
  343. FillStrings;
  344. end;
  345. end;
  346. sqlite_finalize(vm, nil);
  347. end;
  348. end.