sqliteds.pas 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. case AType of
  171. ftString:
  172. FGetSqlStr[i] := @Char2SQLStr;
  173. ftMemo:
  174. FGetSqlStr[i] := @Memo2SQLStr;
  175. else
  176. FGetSqlStr[i] := @Num2SQLStr;
  177. end;
  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: PPAnsiChar;
  194. ColCount: Integer;
  195. begin
  196. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(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: PPAnsiChar;
  207. Counter, ColumnCount: Integer;
  208. begin
  209. //Get AutoInc Field initial value
  210. if FAutoIncFieldNo <> -1 then
  211. sqlite_exec(FSqliteHandle, PAnsiChar('Select Max(' + FieldDefs[FAutoIncFieldNo].Name + ') from ' + FTableName),
  212. @GetAutoIncValue, @FNextAutoInc, nil);
  213. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(FEffectiveSQL), 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, @ColumnCount, @ColumnValues, @ColumnNames);
  220. FRowCount := ColumnCount;
  221. //add extra rows for calculated fields
  222. if FCalcFieldList <> nil then
  223. Inc(FRowCount, FCalcFieldList.Count);
  224. FRowBufferSize := (SizeOf(PPAnsiChar) * FRowCount);
  225. while FReturnCode = SQLITE_ROW do
  226. begin
  227. Inc(FRecordCount);
  228. New(TempItem^.Next);
  229. TempItem^.Next^.Previous := TempItem;
  230. TempItem := TempItem^.Next;
  231. GetMem(TempItem^.Row, FRowBufferSize);
  232. for Counter := 0 to ColumnCount - 1 do
  233. TempItem^.Row[Counter] := StrNew(ColumnValues[Counter]);
  234. //initialize calculated fields with nil
  235. for Counter := ColumnCount to FRowCount - 1 do
  236. TempItem^.Row[Counter] := nil;
  237. FReturnCode := sqlite_step(vm, @FRowCount, @ColumnValues, @ColumnNames);
  238. end;
  239. sqlite_finalize(vm, nil);
  240. // Attach EndItem
  241. TempItem^.Next := FEndItem;
  242. FEndItem^.Previous := TempItem;
  243. // Alloc item used in append/insert
  244. GetMem(FSavedEditItem^.Row, FRowBufferSize);
  245. for Counter := 0 to FRowCount - 1 do
  246. FSavedEditItem^.Row[Counter] := nil;
  247. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  248. GetMem(FBeginItem^.Row, FRowBufferSize);
  249. for Counter := 0 to FRowCount - 1 do
  250. FBeginItem^.Row[Counter] := nil;
  251. end;
  252. function TSqliteDataset.GetLastInsertRowId: Int64;
  253. begin
  254. Result := sqlite_last_insert_rowid(FSqliteHandle);
  255. end;
  256. function TSqliteDataset.ReturnString: String;
  257. begin
  258. case FReturnCode of
  259. SQLITE_OK : Result := 'SQLITE_OK';
  260. SQLITE_ERROR : Result := 'SQLITE_ERROR';
  261. SQLITE_INTERNAL : Result := 'SQLITE_INTERNAL';
  262. SQLITE_PERM : Result := 'SQLITE_PERM';
  263. SQLITE_ABORT : Result := 'SQLITE_ABORT';
  264. SQLITE_BUSY : Result := 'SQLITE_BUSY';
  265. SQLITE_LOCKED : Result := 'SQLITE_LOCKED';
  266. SQLITE_NOMEM : Result := 'SQLITE_NOMEM';
  267. SQLITE_READONLY : Result := 'SQLITE_READONLY';
  268. SQLITE_INTERRUPT : Result := 'SQLITE_INTERRUPT';
  269. SQLITE_IOERR : Result := 'SQLITE_IOERR';
  270. SQLITE_CORRUPT : Result := 'SQLITE_CORRUPT';
  271. SQLITE_NOTFOUND : Result := 'SQLITE_NOTFOUND';
  272. SQLITE_FULL : Result := 'SQLITE_FULL';
  273. SQLITE_CANTOPEN : Result := 'SQLITE_CANTOPEN';
  274. SQLITE_PROTOCOL : Result := 'SQLITE_PROTOCOL';
  275. SQLITE_EMPTY : Result := 'SQLITE_EMPTY';
  276. SQLITE_SCHEMA : Result := 'SQLITE_SCHEMA';
  277. SQLITE_TOOBIG : Result := 'SQLITE_TOOBIG';
  278. SQLITE_CONSTRAINT : Result := 'SQLITE_CONSTRAINT';
  279. SQLITE_MISMATCH : Result := 'SQLITE_MISMATCH';
  280. SQLITE_MISUSE : Result := 'SQLITE_MISUSE';
  281. SQLITE_NOLFS : Result := 'SQLITE_NOLFS';
  282. SQLITE_AUTH : Result := 'SQLITE_AUTH';
  283. SQLITE_FORMAT : Result := 'SQLITE_FORMAT';
  284. SQLITE_RANGE : Result := 'SQLITE_RANGE';
  285. SQLITE_ROW :
  286. begin
  287. Result := 'SQLITE_ROW - not an error';
  288. Exit;
  289. end;
  290. SQLITE_DONE :
  291. begin
  292. Result := 'SQLITE_DONE - not an error';
  293. Exit;
  294. end;
  295. else
  296. Result := 'Unknown Return Value';
  297. end;
  298. Result := Result + ' - ' + sqlite_error_string(FReturnCode);
  299. end;
  300. function TSqliteDataset.GetSqliteEncoding: String;
  301. begin
  302. Result := String(sqlite_encoding);
  303. end;
  304. class function TSqliteDataset.SqliteVersion: String;
  305. begin
  306. Result := String(sqlite_version);
  307. end;
  308. function TSqliteDataset.QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects: Boolean): String;
  309. var
  310. vm: Pointer;
  311. ColumnNames, ColumnValues: PPAnsiChar;
  312. ColCount: Integer;
  313. procedure FillStrings;
  314. begin
  315. while FReturnCode = SQLITE_ROW do
  316. begin
  317. AStrList.Add(String(ColumnValues[0]));
  318. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  319. end;
  320. end;
  321. procedure FillStringsAndObjects;
  322. begin
  323. while FReturnCode = SQLITE_ROW do
  324. begin
  325. // I know, this code is really dirty!!
  326. AStrList.AddObject(String(ColumnValues[0]),
  327. TObject(PtrInt(StrToInt(String(ColumnValues[1])))));
  328. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  329. end;
  330. end;
  331. begin
  332. if FSqliteHandle = nil then
  333. GetSqliteHandle;
  334. Result := '';
  335. FReturnCode := sqlite_compile(FSqliteHandle, PAnsiChar(ASQL), nil, @vm, nil);
  336. if FReturnCode <> SQLITE_OK then
  337. DatabaseError(ReturnString,Self);
  338. FReturnCode := sqlite_step(vm, @ColCount, @ColumnValues, @ColumnNames);
  339. if (FReturnCode = SQLITE_ROW) and (ColCount > 0) then
  340. begin
  341. Result := String(ColumnValues[0]);
  342. if AStrList <> nil then
  343. begin
  344. if FillObjects and (ColCount > 1) then
  345. FillStringsAndObjects
  346. else
  347. FillStrings;
  348. end;
  349. end;
  350. sqlite_finalize(vm, nil);
  351. end;
  352. end.