sqlite3ds.pas 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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., 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. { 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(FieldDefs.MakeNameUnique(String(sqlite3_column_name(vm, i))), AType, DataSize);
  221. //Set the pchar2sql function
  222. case AType of
  223. ftString:
  224. FGetSqlStr[i] := @Char2SQLStr;
  225. ftMemo:
  226. FGetSqlStr[i] := @Memo2SQLStr;
  227. else
  228. FGetSqlStr[i] := @Num2SQLStr;
  229. end;
  230. {$ifdef DEBUG_SQLITEDS}
  231. WriteLn(' Field[', i, '] Name: ', sqlite3_column_name(vm, i));
  232. WriteLn(' Field[', i, '] Type: ', sqlite3_column_decltype(vm, i));
  233. {$endif}
  234. end;
  235. sqlite3_finalize(vm);
  236. {$ifdef DEBUG_SQLITEDS}
  237. WriteLn(' FieldDefs.Count: ', FieldDefs.Count);
  238. {$endif}
  239. end;
  240. function TSqlite3Dataset.GetRowsAffected: Integer;
  241. begin
  242. Result := sqlite3_changes(FSqliteHandle);
  243. end;
  244. procedure TSqlite3Dataset.ExecuteDirect(const ASQL: String);
  245. var
  246. vm: Pointer;
  247. begin
  248. FReturnCode := sqlite3_prepare_v2(FSqliteHandle, PAnsiChar(ASQL), -1, @vm, nil);
  249. if FReturnCode <> SQLITE_OK then
  250. DatabaseError(ReturnString, Self);
  251. FReturnCode := sqlite3_step(vm);
  252. sqlite3_finalize(vm);
  253. end;
  254. procedure TSqlite3Dataset.BuildLinkedList;
  255. var
  256. TempItem: PDataRecord;
  257. vm: Pointer;
  258. Counter, ColumnCount: Integer;
  259. begin
  260. //Get AutoInc Field initial value
  261. if FAutoIncFieldNo <> -1 then
  262. sqlite3_exec(FSqliteHandle, PAnsiChar('Select Max(' + FieldDefs[FAutoIncFieldNo].Name +
  263. ') from ' + FTableName), @GetAutoIncValue, @FNextAutoInc, nil);
  264. FReturnCode := sqlite3_prepare_v2(FSqliteHandle, PAnsiChar(FEffectiveSQL), -1, @vm, nil);
  265. if FReturnCode <> SQLITE_OK then
  266. DatabaseError(ReturnString, Self);
  267. FDataAllocated := True;
  268. TempItem := FBeginItem;
  269. FRecordCount := 0;
  270. ColumnCount := sqlite3_column_count(vm);
  271. FRowCount := ColumnCount;
  272. //add extra rows for calculated fields
  273. if FCalcFieldList <> nil then
  274. Inc(FRowCount, FCalcFieldList.Count);
  275. FRowBufferSize := (SizeOf(PPAnsiChar) * FRowCount);
  276. FReturnCode := sqlite3_step(vm);
  277. while FReturnCode = SQLITE_ROW do
  278. begin
  279. Inc(FRecordCount);
  280. New(TempItem^.Next);
  281. TempItem^.Next^.Previous := TempItem;
  282. TempItem := TempItem^.Next;
  283. GetMem(TempItem^.Row, FRowBufferSize);
  284. for Counter := 0 to ColumnCount - 1 do
  285. TempItem^.Row[Counter] := StrBufNew(sqlite3_column_text(vm, Counter), sqlite3_column_bytes(vm, Counter) + 1);
  286. //initialize calculated fields with nil
  287. for Counter := ColumnCount to FRowCount - 1 do
  288. TempItem^.Row[Counter] := nil;
  289. FReturnCode := sqlite3_step(vm);
  290. end;
  291. sqlite3_finalize(vm);
  292. // Attach EndItem
  293. TempItem^.Next := FEndItem;
  294. FEndItem^.Previous := TempItem;
  295. // Alloc temporary item used in edit
  296. GetMem(FSavedEditItem^.Row, FRowBufferSize);
  297. for Counter := 0 to FRowCount - 1 do
  298. FSavedEditItem^.Row[Counter] := nil;
  299. // Fill FBeginItem.Row with nil -> necessary for avoid exceptions in empty datasets
  300. GetMem(FBeginItem^.Row, FRowBufferSize);
  301. //Todo: see if is better to nullif using FillDWord
  302. for Counter := 0 to FRowCount - 1 do
  303. FBeginItem^.Row[Counter] := nil;
  304. end;
  305. function TSqlite3Dataset.GetLastInsertRowId: Int64;
  306. begin
  307. Result := sqlite3_last_insert_rowid(FSqliteHandle);
  308. end;
  309. function TSqlite3Dataset.ReturnString: String;
  310. begin
  311. Result := SqliteCode2Str(FReturnCode) + ' - ' + sqlite3_errmsg(FSqliteHandle);
  312. end;
  313. class function TSqlite3Dataset.SqliteVersion: String;
  314. begin
  315. Result := String(sqlite3_version());
  316. end;
  317. function TSqlite3Dataset.QuickQuery(const ASQL: String; const AStrList: TStrings; FillObjects:Boolean): String;
  318. var
  319. vm: Pointer;
  320. procedure FillStrings;
  321. begin
  322. while FReturnCode = SQLITE_ROW do
  323. begin
  324. AStrList.Add(String(sqlite3_column_text(vm,0)));
  325. FReturnCode := sqlite3_step(vm);
  326. end;
  327. end;
  328. procedure FillStringsAndObjects;
  329. begin
  330. while FReturnCode = SQLITE_ROW do
  331. begin
  332. AStrList.AddObject(String(sqlite3_column_text(vm, 0)),
  333. TObject(PtrInt(sqlite3_column_int(vm, 1))));
  334. FReturnCode := sqlite3_step(vm);
  335. end;
  336. end;
  337. begin
  338. if FSqliteHandle = nil then
  339. GetSqliteHandle;
  340. Result := '';
  341. FReturnCode := sqlite3_prepare_v2(FSqliteHandle,PAnsiChar(ASQL), -1, @vm, nil);
  342. if FReturnCode <> SQLITE_OK then
  343. DatabaseError(ReturnString, Self);
  344. FReturnCode := sqlite3_step(vm);
  345. if (FReturnCode = SQLITE_ROW) and (sqlite3_column_count(vm) > 0) then
  346. begin
  347. Result := String(sqlite3_column_text(vm, 0));
  348. if AStrList <> nil then
  349. begin
  350. if FillObjects and (sqlite3_column_count(vm) > 1) then
  351. FillStringsAndObjects
  352. else
  353. FillStrings;
  354. end;
  355. end;
  356. sqlite3_finalize(vm);
  357. end;
  358. end.