sqlite3ds.pas 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. unit Sqlite3DS;
  2. {
  3. This is TSqlite3Dataset, 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. { TSqlite3Dataset }
  36. TSqlite3Dataset = class(TCustomSqliteDataset)
  37. protected
  38. procedure BuildLinkedList; override;
  39. function GetLastInsertRowId: Int64; override;
  40. function GetRowsAffected:Integer; override;
  41. procedure InternalCloseHandle; override;
  42. function InternalGetHandle: Pointer; override;
  43. procedure RetrieveFieldDefs; override;
  44. function SqliteExec(ASQL: PAnsiChar; ACallback: TSqliteCdeclCallback; Data: Pointer): Integer; override;
  45. public
  46. procedure ExecuteDirect(const ASQL: String); override;
  47. function QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects: Boolean): String; override;
  48. function ReturnString: String; override;
  49. class function SqliteVersion: String; override;
  50. end;
  51. implementation
  52. uses
  53. sqlite3, db, strutils;
  54. function SqliteCode2Str(Code: Integer): String;
  55. begin
  56. case Code of
  57. SQLITE_OK : Result := 'SQLITE_OK';
  58. SQLITE_ERROR : Result := 'SQLITE_ERROR';
  59. SQLITE_INTERNAL : Result := 'SQLITE_INTERNAL';
  60. SQLITE_PERM : Result := 'SQLITE_PERM';
  61. SQLITE_ABORT : Result := 'SQLITE_ABORT';
  62. SQLITE_BUSY : Result := 'SQLITE_BUSY';
  63. SQLITE_LOCKED : Result := 'SQLITE_LOCKED';
  64. SQLITE_NOMEM : Result := 'SQLITE_NOMEM';
  65. SQLITE_READONLY : Result := 'SQLITE_READONLY';
  66. SQLITE_INTERRUPT : Result := 'SQLITE_INTERRUPT';
  67. SQLITE_IOERR : Result := 'SQLITE_IOERR';
  68. SQLITE_CORRUPT : Result := 'SQLITE_CORRUPT';
  69. SQLITE_NOTFOUND : Result := 'SQLITE_NOTFOUND';
  70. SQLITE_FULL : Result := 'SQLITE_FULL';
  71. SQLITE_CANTOPEN : Result := 'SQLITE_CANTOPEN';
  72. SQLITE_PROTOCOL : Result := 'SQLITE_PROTOCOL';
  73. SQLITE_EMPTY : Result := 'SQLITE_EMPTY';
  74. SQLITE_SCHEMA : Result := 'SQLITE_SCHEMA';
  75. SQLITE_TOOBIG : Result := 'SQLITE_TOOBIG';
  76. SQLITE_CONSTRAINT : Result := 'SQLITE_CONSTRAINT';
  77. SQLITE_MISMATCH : Result := 'SQLITE_MISMATCH';
  78. SQLITE_MISUSE : Result := 'SQLITE_MISUSE';
  79. SQLITE_NOLFS : Result := 'SQLITE_NOLFS';
  80. SQLITE_AUTH : Result := 'SQLITE_AUTH';
  81. SQLITE_FORMAT : Result := 'SQLITE_FORMAT';
  82. SQLITE_RANGE : Result := 'SQLITE_RANGE';
  83. SQLITE_ROW : Result := 'SQLITE_ROW';
  84. SQLITE_NOTADB : Result := 'SQLITE_NOTADB';
  85. SQLITE_DONE : Result := 'SQLITE_DONE';
  86. else
  87. Result := 'Unknown Return Value';
  88. end;
  89. end;
  90. function GetAutoIncValue(NextValue: Pointer; Columns: Integer; ColumnValues: PPAnsiChar; ColumnNames: PPAnsiChar): Integer; cdecl;
  91. var
  92. CodeError, TempInt: Integer;
  93. begin
  94. TempInt := 0;
  95. if ColumnValues[0] <> nil then
  96. begin
  97. Val(String(ColumnValues[0]), TempInt, CodeError);
  98. if CodeError <> 0 then
  99. DatabaseError('TSqlite3Dataset: Error trying to get last autoinc value');
  100. end;
  101. Integer(NextValue^) := Succ(TempInt);
  102. Result := 1;
  103. end;
  104. { TSqlite3Dataset }
  105. function TSqlite3Dataset.SqliteExec(ASQL: PAnsiChar; ACallback: TSqliteCdeclCallback; Data: Pointer): Integer;
  106. begin
  107. Result := sqlite3_exec(FSqliteHandle, ASQL, ACallback, Data, nil);
  108. end;
  109. procedure TSqlite3Dataset.InternalCloseHandle;
  110. begin
  111. sqlite3_close(FSqliteHandle);
  112. FSqliteHandle := nil;
  113. //todo:handle return data
  114. end;
  115. function TSqlite3Dataset.InternalGetHandle: Pointer;
  116. const
  117. CheckFileSql = 'Select Name from sqlite_master LIMIT 1';
  118. var
  119. vm: Pointer;
  120. ErrorStr: String;
  121. begin
  122. sqlite3_open(PAnsiChar(FFileName), @Result);
  123. //sqlite3_open returns SQLITE_OK even for invalid files
  124. //do additional check here
  125. FReturnCode := sqlite3_prepare_v2(Result, CheckFileSql, -1, @vm, nil);
  126. if FReturnCode <> SQLITE_OK then
  127. begin
  128. ErrorStr := SqliteCode2Str(FReturnCode) + ' - ' + sqlite3_errmsg(Result);
  129. sqlite3_close(Result);
  130. DatabaseError(ErrorStr, Self);
  131. end;
  132. sqlite3_finalize(vm);
  133. end;
  134. procedure TSqlite3Dataset.RetrieveFieldDefs;
  135. var
  136. vm: Pointer;
  137. ColumnStr: String;
  138. i, ColumnCount, DataSize: Integer;
  139. AType: TFieldType;
  140. begin
  141. {$ifdef DEBUG_SQLITEDS}
  142. WriteLn('##TSqlite3Dataset.InternalInitFieldDefs##');
  143. {$endif}
  144. FAutoIncFieldNo := -1;
  145. FieldDefs.Clear;
  146. FReturnCode := sqlite3_prepare_v2(FSqliteHandle, PAnsiChar(FEffectiveSQL), -1, @vm, nil);
  147. if FReturnCode <> SQLITE_OK then
  148. DatabaseError(ReturnString, Self);
  149. sqlite3_step(vm);
  150. ColumnCount := sqlite3_column_count(vm);
  151. //Prepare the array of pchar2sql functions
  152. SetLength(FGetSqlStr, ColumnCount);
  153. for i := 0 to ColumnCount - 1 do
  154. begin
  155. DataSize := 0;
  156. ColumnStr := UpperCase(String(sqlite3_column_decltype(vm, i)));
  157. if (ColumnStr = 'INTEGER') or (ColumnStr = 'INT') then
  158. begin
  159. if AutoIncrementKey and (UpperCase(String(sqlite3_column_name(vm, i))) = UpperCase(PrimaryKey)) then
  160. begin
  161. AType := ftAutoInc;
  162. FAutoIncFieldNo := i;
  163. end
  164. else
  165. AType := ftInteger;
  166. end else if Pos('VARCHAR', ColumnStr) = 1 then
  167. begin
  168. AType := ftString;
  169. DataSize := StrToIntDef(Trim(ExtractDelimited(2, ColumnStr, ['(', ')'])), DefaultStringSize);
  170. end else if Pos('BOOL', ColumnStr) = 1 then
  171. begin
  172. AType := ftBoolean;
  173. end else if Pos('AUTOINC', ColumnStr) = 1 then
  174. begin
  175. AType := ftAutoInc;
  176. if FAutoIncFieldNo = -1 then
  177. FAutoIncFieldNo := i;
  178. end else if (Pos('FLOAT', ColumnStr) = 1) or (Pos('NUMERIC', ColumnStr) = 1) then
  179. begin
  180. AType := ftFloat;
  181. end else if (ColumnStr = 'DATETIME') then
  182. begin
  183. AType := ftDateTime;
  184. end else if (ColumnStr = 'DATE') then
  185. begin
  186. AType := ftDate;
  187. end else if (ColumnStr = 'LARGEINT') or (ColumnStr = 'BIGINT') then
  188. begin
  189. AType := ftLargeInt;
  190. end else if (ColumnStr = 'TIME') then
  191. begin
  192. AType := ftTime;
  193. end else if (ColumnStr = 'TEXT') then
  194. begin
  195. AType := ftMemo;
  196. end else if (ColumnStr = 'CURRENCY') then
  197. begin
  198. AType := ftCurrency;
  199. end else if (ColumnStr = 'WORD') then
  200. begin
  201. AType := ftWord;
  202. end else if (ColumnStr = '') then
  203. begin
  204. case sqlite3_column_type(vm, i) of
  205. SQLITE_INTEGER:
  206. AType := ftInteger;
  207. SQLITE_FLOAT:
  208. AType := ftFloat;
  209. else
  210. begin
  211. AType := ftString;
  212. DataSize := DefaultStringSize;
  213. end;
  214. end;
  215. end else
  216. begin
  217. AType := ftString;
  218. DataSize := DefaultStringSize;
  219. end;
  220. FieldDefs.Add(String(sqlite3_column_name(vm, i)), AType, DataSize);
  221. //Set the pchar2sql function
  222. if AType in [ftString, ftMemo] then
  223. FGetSqlStr[i] := @Char2SQLStr
  224. else
  225. FGetSqlStr[i] := @Num2SQLStr;
  226. {$ifdef DEBUG_SQLITEDS}
  227. WriteLn(' Field[', i, '] Name: ', sqlite3_column_name(vm, i));
  228. WriteLn(' Field[', i, '] Type: ', sqlite3_column_decltype(vm, i));
  229. {$endif}
  230. end;
  231. sqlite3_finalize(vm);
  232. {$ifdef DEBUG_SQLITEDS}
  233. WriteLn(' FieldDefs.Count: ', FieldDefs.Count);
  234. {$endif}
  235. end;
  236. function TSqlite3Dataset.GetRowsAffected: Integer;
  237. begin
  238. Result := sqlite3_changes(FSqliteHandle);
  239. end;
  240. procedure TSqlite3Dataset.ExecuteDirect(const ASQL: String);
  241. var
  242. vm: Pointer;
  243. begin
  244. FReturnCode := sqlite3_prepare_v2(FSqliteHandle, PAnsiChar(ASQL), -1, @vm, nil);
  245. if FReturnCode <> SQLITE_OK then
  246. DatabaseError(ReturnString, Self);
  247. FReturnCode := sqlite3_step(vm);
  248. sqlite3_finalize(vm);
  249. end;
  250. procedure TSqlite3Dataset.BuildLinkedList;
  251. var
  252. TempItem: PDataRecord;
  253. vm: Pointer;
  254. Counter, ColumnCount: Integer;
  255. begin
  256. //Get AutoInc Field initial value
  257. if FAutoIncFieldNo <> -1 then
  258. sqlite3_exec(FSqliteHandle, PAnsiChar('Select Max(' + FieldDefs[FAutoIncFieldNo].Name +
  259. ') from ' + FTableName), @GetAutoIncValue, @FNextAutoInc, nil);
  260. FReturnCode := sqlite3_prepare_v2(FSqliteHandle, PAnsiChar(FEffectiveSQL), -1, @vm, nil);
  261. if FReturnCode <> SQLITE_OK then
  262. DatabaseError(ReturnString, Self);
  263. FDataAllocated := True;
  264. TempItem := FBeginItem;
  265. FRecordCount := 0;
  266. ColumnCount := sqlite3_column_count(vm);
  267. FRowCount := ColumnCount;
  268. //add extra rows for calculated fields
  269. if FCalcFieldList <> nil then
  270. Inc(FRowCount, FCalcFieldList.Count);
  271. FRowBufferSize := (SizeOf(PPAnsiChar) * FRowCount);
  272. FReturnCode := sqlite3_step(vm);
  273. while FReturnCode = SQLITE_ROW do
  274. begin
  275. Inc(FRecordCount);
  276. New(TempItem^.Next);
  277. TempItem^.Next^.Previous := TempItem;
  278. TempItem := TempItem^.Next;
  279. GetMem(TempItem^.Row, FRowBufferSize);
  280. for Counter := 0 to ColumnCount - 1 do
  281. TempItem^.Row[Counter] := StrNew(sqlite3_column_text(vm, Counter));
  282. //initialize calculated fields with nil
  283. for Counter := ColumnCount to FRowCount - 1 do
  284. TempItem^.Row[Counter] := nil;
  285. FReturnCode := sqlite3_step(vm);
  286. end;
  287. sqlite3_finalize(vm);
  288. // Attach EndItem
  289. TempItem^.Next := FEndItem;
  290. FEndItem^.Previous := TempItem;
  291. // Alloc temporary item used in edit
  292. GetMem(FSavedEditItem^.Row, FRowBufferSize);
  293. for Counter := 0 to FRowCount - 1 do
  294. FSavedEditItem^.Row[Counter] := nil;
  295. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  296. GetMem(FBeginItem^.Row, FRowBufferSize);
  297. //Todo: see if is better to nullif using FillDWord
  298. for Counter := 0 to FRowCount - 1 do
  299. FBeginItem^.Row[Counter] := nil;
  300. end;
  301. function TSqlite3Dataset.GetLastInsertRowId: Int64;
  302. begin
  303. Result := sqlite3_last_insert_rowid(FSqliteHandle);
  304. end;
  305. function TSqlite3Dataset.ReturnString: String;
  306. begin
  307. Result := SqliteCode2Str(FReturnCode) + ' - ' + sqlite3_errmsg(FSqliteHandle);
  308. end;
  309. class function TSqlite3Dataset.SqliteVersion: String;
  310. begin
  311. Result := String(sqlite3_version());
  312. end;
  313. function TSqlite3Dataset.QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects:Boolean): String;
  314. var
  315. vm: Pointer;
  316. procedure FillStrings;
  317. begin
  318. while FReturnCode = SQLITE_ROW do
  319. begin
  320. AStrList.Add(String(sqlite3_column_text(vm,0)));
  321. FReturnCode := sqlite3_step(vm);
  322. end;
  323. end;
  324. procedure FillStringsAndObjects;
  325. begin
  326. while FReturnCode = SQLITE_ROW do
  327. begin
  328. AStrList.AddObject(String(sqlite3_column_text(vm, 0)),
  329. TObject(PtrInt(sqlite3_column_int(vm, 1))));
  330. FReturnCode := sqlite3_step(vm);
  331. end;
  332. end;
  333. begin
  334. if FSqliteHandle = nil then
  335. GetSqliteHandle;
  336. Result := '';
  337. FReturnCode := sqlite3_prepare_v2(FSqliteHandle,PAnsiChar(ASQL), -1, @vm, nil);
  338. if FReturnCode <> SQLITE_OK then
  339. DatabaseError(ReturnString, Self);
  340. FReturnCode := sqlite3_step(vm);
  341. if (FReturnCode = SQLITE_ROW) and (sqlite3_column_count(vm) > 0) then
  342. begin
  343. Result := String(sqlite3_column_text(vm, 0));
  344. if AStrList <> nil then
  345. begin
  346. if FillObjects and (sqlite3_column_count(vm) > 1) then
  347. FillStringsAndObjects
  348. else
  349. FillStrings;
  350. end;
  351. end;
  352. sqlite3_finalize(vm);
  353. end;
  354. end.