mysqlconn.inc 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. {$mode objfpc}{$H+}
  2. interface
  3. uses
  4. Classes, SysUtils,bufdataset,sqldb,db,dynlibs,
  5. {$IfDef mysql50}
  6. mysql50dyn;
  7. {$ELSE}
  8. {$IfDef mysql41}
  9. mysql41dyn;
  10. {$ELSE}
  11. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  12. mysql40dyn;
  13. {$ELSE}
  14. mysql40dyn;
  15. {$EndIf}
  16. {$EndIf}
  17. {$EndIf}
  18. Const
  19. {$IfDef mysql50}
  20. MySQLVersion = '5.0';
  21. {$ELSE}
  22. {$IfDef mysql41}
  23. MySQLVersion = '4.1';
  24. {$ELSE}
  25. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  26. MySQLVersion = '4.0';
  27. {$ELSE}
  28. MySQLVersion = '4.0';
  29. {$EndIf}
  30. {$EndIf}
  31. {$EndIf}
  32. Type
  33. TTransactionName = Class(TSQLHandle)
  34. protected
  35. end;
  36. { TCursorName }
  37. TCursorName = Class(TSQLCursor)
  38. protected
  39. FRes: PMYSQL_RES; { Record pointer }
  40. FNeedData : Boolean;
  41. FStatement : String;
  42. Row : MYSQL_ROW;
  43. RowsAffected : QWord;
  44. LastInsertID : QWord;
  45. ParamBinding : TParamBinding;
  46. ParamReplaceString : String;
  47. MapDSRowToMSQLRow : array of integer;
  48. end;
  49. { TConnectionName }
  50. TConnectionName = class (TSQLConnection)
  51. private
  52. FHostInfo: String;
  53. FServerInfo: String;
  54. FMySQL : PMySQL;
  55. function GetClientInfo: string;
  56. function GetServerStatus: String;
  57. procedure ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  58. procedure ExecuteDirectMySQL(const query : string);
  59. function EscapeString(const Str : string) : string;
  60. protected
  61. function StrToStatementType(s : string) : TStatementType; override;
  62. Procedure ConnectToServer; virtual;
  63. Procedure SelectDatabase; virtual;
  64. function MySQLDataType(AType: enum_field_types; ASize, ADecimals: Integer; var NewType: TFieldType; var NewSize: Integer): Boolean;
  65. function MySQLWriteData(AType: enum_field_types;ASize: Integer; AFieldType: TFieldType; Source, Dest: PChar; out CreateBlob : boolean): Boolean;
  66. // SQLConnection methods
  67. procedure DoInternalConnect; override;
  68. procedure DoInternalDisconnect; override;
  69. function GetHandle : pointer; override;
  70. function GetAsSQLText(Field : TField) : string; overload; override;
  71. function GetAsSQLText(Param : TParam) : string; overload; override;
  72. Function AllocateCursorHandle : TSQLCursor; override;
  73. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  74. Function AllocateTransactionHandle : TSQLHandle; override;
  75. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  76. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  77. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  78. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams); override;
  79. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  80. function Fetch(cursor : TSQLCursor) : boolean; override;
  81. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  82. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor;ATransaction : TSQLTransaction); override;
  83. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  84. function Commit(trans : TSQLHandle) : boolean; override;
  85. function RollBack(trans : TSQLHandle) : boolean; override;
  86. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  87. procedure CommitRetaining(trans : TSQLHandle); override;
  88. procedure RollBackRetaining(trans : TSQLHandle); override;
  89. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  90. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  91. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  92. Public
  93. constructor Create(AOwner : TComponent); override;
  94. procedure GetFieldNames(const TableName : string; List : TStrings); override;
  95. procedure GetTableNames(List : TStrings; SystemTables : Boolean = false); override;
  96. procedure CreateDB; override;
  97. procedure DropDB; override;
  98. Property ServerInfo : String Read FServerInfo;
  99. Property HostInfo : String Read FHostInfo;
  100. property ClientInfo: string read GetClientInfo;
  101. property ServerStatus : String read GetServerStatus;
  102. published
  103. property DatabaseName;
  104. property HostName;
  105. property KeepConnection;
  106. property LoginPrompt;
  107. property Params;
  108. property Port stored false;
  109. property OnLogin;
  110. end;
  111. { TMySQLConnectionDef }
  112. TMySQLConnectionDef = Class(TConnectionDef)
  113. Class Function TypeName : String; override;
  114. Class Function ConnectionClass : TSQLConnectionClass; override;
  115. Class Function Description : String; override;
  116. end;
  117. EMySQLError = Class(Exception);
  118. {$IfDef mysql50}
  119. TMySQL50Connection = Class(TConnectionName);
  120. TMySQL50ConnectionDef = Class(TMySQLConnectionDef);
  121. TMySQL50Transaction = Class(TTransactionName);
  122. TMySQL50Cursor = Class(TCursorName);
  123. {$ELSE}
  124. {$IfDef mysql41}
  125. TMySQL41Connection = Class(TConnectionName);
  126. TMySQL41ConnectionDef = Class(TMySQLConnectionDef);
  127. TMySQL41Transaction = Class(TTransactionName);
  128. TMySQL41Cursor = Class(TCursorName);
  129. {$ELSE}
  130. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  131. TMySQLConnection = Class(TConnectionName);
  132. TMySQL40ConnectionDef = Class(TMySQLConnectionDef);
  133. TMySQLTransaction = Class(TTransactionName);
  134. TMySQLCursor = Class(TCursorName);
  135. {$ELSE}
  136. TMySQL40Connection = Class(TConnectionName);
  137. TMySQL40ConnectionDef = Class(TMySQLConnectionDef);
  138. TMySQL40Transaction = Class(TTransactionName);
  139. TMySQL40Cursor = Class(TCursorName);
  140. {$EndIf}
  141. {$EndIf}
  142. {$EndIf}
  143. implementation
  144. uses dbconst,ctypes,strutils;
  145. { TConnectionName }
  146. Resourcestring
  147. SErrServerConnectFailed = 'Server connect failed.';
  148. SErrDatabaseSelectFailed = 'failed to select database: %s';
  149. SErrDatabaseCreate = 'Failed to create database: %s';
  150. SErrDatabaseDrop = 'Failed to drop database: %s';
  151. SErrNoData = 'No data for record';
  152. SErrExecuting = 'Error executing query: %s';
  153. SErrFetchingdata = 'Error fetching row data: %s';
  154. SErrGettingResult = 'Error getting result set: %s';
  155. SErrNoQueryResult = 'No result from query.';
  156. SErrNotversion50 = 'TMySQL50Connection can not work with the installed MySQL client version (%s).';
  157. SErrNotversion41 = 'TMySQL41Connection can not work with the installed MySQL client version (%s).';
  158. SErrNotversion40 = 'TMySQL40Connection can not work with the installed MySQL client version (%s).';
  159. Procedure MySQlError(R : PMySQL;Msg: String;Comp : TComponent);
  160. Var
  161. MySQLMsg : String;
  162. begin
  163. If (R<>Nil) then
  164. begin
  165. MySQLMsg:=Strpas(mysql_error(R));
  166. DatabaseErrorFmt(Msg,[MySQLMsg],Comp);
  167. end
  168. else
  169. DatabaseError(Msg,Comp);
  170. end;
  171. function TConnectionName.StrToStatementType(s : string) : TStatementType;
  172. begin
  173. S:=Lowercase(s);
  174. if s = 'show' then exit(stSelect);
  175. result := inherited StrToStatementType(s);
  176. end;
  177. function TConnectionName.GetClientInfo: string;
  178. begin
  179. // To make it possible to call this if there's no connection yet
  180. InitialiseMysql;
  181. Try
  182. Result:=strpas(mysql_get_client_info());
  183. Finally
  184. ReleaseMysql;
  185. end;
  186. end;
  187. function TConnectionName.GetServerStatus: String;
  188. begin
  189. CheckConnected;
  190. Result := mysql_stat(FMYSQL);
  191. end;
  192. procedure TConnectionName.ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  193. Var
  194. APort : Cardinal;
  195. begin
  196. HMySQL := mysql_init(HMySQL);
  197. APort:=Abs(StrToIntDef(Params.Values['Port'],0));
  198. HMySQL:=mysql_real_connect(HMySQL,PChar(H),PChar(U),Pchar(P),Nil,APort,Nil,0);
  199. If (HMySQL=Nil) then
  200. MySQlError(Nil,SErrServerConnectFailed,Self);
  201. end;
  202. function TConnectionName.GetAsSQLText(Field : TField) : string;
  203. var esc_str : pchar;
  204. begin
  205. if (not assigned(field)) or field.IsNull then Result := 'Null'
  206. else if field.DataType = ftString then
  207. Result := '''' + EscapeString(field.AsString) + ''''
  208. else Result := inherited GetAsSqlText(field);
  209. end;
  210. function TConnectionName.GetAsSQLText(Param: TParam) : string;
  211. var esc_str : pchar;
  212. begin
  213. if (not assigned(param)) or param.IsNull then Result := 'Null'
  214. else if param.DataType in [ftString,ftBlob,ftMemo] then
  215. Result := '''' + EscapeString(Param.AsString) + ''''
  216. else Result := inherited GetAsSqlText(Param);
  217. end;
  218. procedure TConnectionName.ConnectToServer;
  219. Var
  220. H,U,P : String;
  221. begin
  222. H:=HostName;
  223. U:=UserName;
  224. P:=Password;
  225. ConnectMySQL(FMySQL,pchar(H),pchar(U),pchar(P));
  226. FServerInfo := strpas(mysql_get_server_info(FMYSQL));
  227. FHostInfo := strpas(mysql_get_host_info(FMYSQL));
  228. end;
  229. procedure TConnectionName.SelectDatabase;
  230. begin
  231. if mysql_select_db(FMySQL,pchar(DatabaseName))<>0 then
  232. MySQLError(FMySQL,SErrDatabaseSelectFailed,Self);
  233. end;
  234. procedure TConnectionName.CreateDB;
  235. begin
  236. ExecuteDirectMySQL('CREATE DATABASE ' +DatabaseName);
  237. end;
  238. procedure TConnectionName.DropDB;
  239. begin
  240. ExecuteDirectMySQL('DROP DATABASE ' +DatabaseName);
  241. end;
  242. procedure TConnectionName.ExecuteDirectMySQL(const query : string);
  243. var H,U,P : String;
  244. AMySQL : PMySQL;
  245. begin
  246. CheckDisConnected;
  247. InitialiseMysql;
  248. H:=HostName;
  249. U:=UserName;
  250. P:=Password;
  251. AMySQL := nil;
  252. ConnectMySQL(AMySQL,pchar(H),pchar(U),pchar(P));
  253. if mysql_query(AMySQL,pchar(query))<>0 then
  254. MySQLError(AMySQL,Format(SErrExecuting,[StrPas(mysql_error(AMySQL))]),Self);
  255. mysql_close(AMySQL);
  256. ReleaseMysql;
  257. end;
  258. function TConnectionName.EscapeString(const Str: string): string;
  259. var Len : integer;
  260. begin
  261. SetLength(result,length(str)*2+1);
  262. Len := mysql_real_escape_string(FMySQL,pchar(Result),pchar(Str),length(Str));
  263. SetLength(result,Len);
  264. end;
  265. procedure TConnectionName.DoInternalConnect;
  266. begin
  267. InitialiseMysql;
  268. {$IFDEF mysql50}
  269. if copy(strpas(mysql_get_client_info()),1,3)<>'5.0' then
  270. Raise EInOutError.CreateFmt(SErrNotversion50,[strpas(mysql_get_client_info())]);
  271. {$ELSE}
  272. {$IFDEF mysql41}
  273. if copy(strpas(mysql_get_client_info()),1,3)<>'4.1' then
  274. Raise EInOutError.CreateFmt(SErrNotversion41,[strpas(mysql_get_client_info())]);
  275. {$ELSE}
  276. if copy(strpas(mysql_get_client_info()),1,3)<>'4.0' then
  277. Raise EInOutError.CreateFmt(SErrNotversion40,[strpas(mysql_get_client_info())]);
  278. {$ENDIF}
  279. {$ENDIF}
  280. inherited DoInternalConnect;
  281. ConnectToServer;
  282. SelectDatabase;
  283. end;
  284. procedure TConnectionName.DoInternalDisconnect;
  285. begin
  286. inherited DoInternalDisconnect;
  287. mysql_close(FMySQL);
  288. FMySQL:=Nil;
  289. ReleaseMysql;
  290. end;
  291. function TConnectionName.GetHandle: pointer;
  292. begin
  293. Result:=FMySQL;
  294. end;
  295. function TConnectionName.AllocateCursorHandle: TSQLCursor;
  296. begin
  297. {$IfDef mysql50}
  298. Result:=TMySQL50Cursor.Create;
  299. {$ELSE}
  300. {$IfDef mysql41}
  301. Result:=TMySQL41Cursor.Create;
  302. {$ELSE}
  303. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  304. Result:=TMySQLCursor.Create;
  305. {$ELSE}
  306. Result:=TMySQL40Cursor.Create;
  307. {$EndIf}
  308. {$EndIf}
  309. {$EndIf}
  310. end;
  311. Procedure TConnectionName.DeAllocateCursorHandle(var cursor : TSQLCursor);
  312. begin
  313. FreeAndNil(cursor);
  314. end;
  315. function TConnectionName.AllocateTransactionHandle: TSQLHandle;
  316. begin
  317. // Result:=TTransactionName.Create;
  318. Result := nil;
  319. end;
  320. procedure TConnectionName.PrepareStatement(cursor: TSQLCursor;
  321. ATransaction: TSQLTransaction; buf: string;AParams : TParams);
  322. begin
  323. // if assigned(AParams) and (AParams.count > 0) then
  324. // DatabaseError('Parameters (not) yet supported for the MySQL SqlDB connection.',self);
  325. With Cursor as TCursorName do
  326. begin
  327. FStatement:=Buf;
  328. if assigned(AParams) and (AParams.count > 0) then
  329. FStatement := AParams.ParseSQL(FStatement,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psSimulated,paramBinding,ParamReplaceString);
  330. if FStatementType=stSelect then
  331. FNeedData:=True;
  332. end
  333. end;
  334. procedure TConnectionName.UnPrepareStatement(cursor: TSQLCursor);
  335. begin
  336. // do nothing
  337. end;
  338. procedure TConnectionName.FreeFldBuffers(cursor: TSQLCursor);
  339. Var
  340. C : TCursorName;
  341. begin
  342. C:=Cursor as TCursorName;
  343. if c.FStatementType=stSelect then
  344. c.FNeedData:=False;
  345. If (C.FRes<>Nil) then
  346. begin
  347. Mysql_free_result(C.FRes);
  348. C.FRes:=Nil;
  349. end;
  350. SetLength(c.MapDSRowToMSQLRow,0);
  351. inherited;
  352. end;
  353. procedure TConnectionName.Execute(cursor: TSQLCursor;
  354. atransaction: tSQLtransaction;AParams : TParams);
  355. Var
  356. C : TCursorName;
  357. i : integer;
  358. ParamNames,ParamValues : array of string;
  359. begin
  360. C:=Cursor as TCursorName;
  361. If (C.FRes=Nil) then
  362. begin
  363. if Assigned(AParams) and (AParams.count > 0) then
  364. begin
  365. setlength(ParamNames,AParams.Count);
  366. setlength(ParamValues,AParams.Count);
  367. for i := 0 to AParams.count -1 do
  368. begin
  369. ParamNames[AParams.count-i-1] := C.ParamReplaceString+inttostr(AParams[i].Index+1);
  370. ParamValues[AParams.count-i-1] := GetAsSQLText(AParams[i]);
  371. end;
  372. // paramreplacestring kan een probleem geven bij postgres als hij niet meer gewoon $ is?
  373. C.FStatement := stringsreplace(C.FStatement,ParamNames,ParamValues,[rfReplaceAll]);
  374. end;
  375. if mysql_query(FMySQL,Pchar(C.FStatement))<>0 then
  376. MySQLError(FMYSQL,Format(SErrExecuting,[StrPas(mysql_error(FMySQL))]),Self)
  377. else
  378. begin
  379. C.RowsAffected := mysql_affected_rows(FMYSQL);
  380. C.LastInsertID := mysql_insert_id(FMYSQL);
  381. if C.FNeedData then
  382. C.FRes:=mysql_store_result(FMySQL);
  383. end;
  384. end;
  385. end;
  386. function TConnectionName.MySQLDataType(AType: enum_field_types; ASize, ADecimals: Integer;
  387. var NewType: TFieldType; var NewSize: Integer): Boolean;
  388. begin
  389. Result := True;
  390. case AType of
  391. FIELD_TYPE_LONGLONG:
  392. begin
  393. NewType := ftLargeint;
  394. NewSize := 0;
  395. end;
  396. FIELD_TYPE_TINY, FIELD_TYPE_SHORT:
  397. begin
  398. NewType := ftSmallint;
  399. NewSize := 0;
  400. end;
  401. FIELD_TYPE_LONG, FIELD_TYPE_INT24:
  402. begin
  403. NewType := ftInteger;
  404. NewSize := 0;
  405. end;
  406. {$ifdef mysql50}
  407. FIELD_TYPE_NEWDECIMAL,
  408. {$endif}
  409. FIELD_TYPE_DECIMAL: if ADecimals < 5 then
  410. begin
  411. NewType := ftBCD;
  412. NewSize := ADecimals;
  413. end
  414. else
  415. begin
  416. NewType := ftFloat;
  417. NewSize := 0;
  418. end;
  419. FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  420. begin
  421. NewType := ftFloat;
  422. NewSize := 0;
  423. end;
  424. FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  425. begin
  426. NewType := ftDateTime;
  427. NewSize := 0;
  428. end;
  429. FIELD_TYPE_DATE:
  430. begin
  431. NewType := ftDate;
  432. NewSize := 0;
  433. end;
  434. FIELD_TYPE_TIME:
  435. begin
  436. NewType := ftTime;
  437. NewSize := 0;
  438. end;
  439. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  440. begin
  441. // Since mysql server version 5.0.3 string-fields with a length of more
  442. // then 256 characters are suported
  443. if ASize>dsMaxStringSize then
  444. begin
  445. NewType := ftMemo;
  446. NewSize := 0;
  447. end
  448. else
  449. begin
  450. NewType := ftString;
  451. NewSize := ASize;
  452. end;
  453. end;
  454. FIELD_TYPE_BLOB:
  455. begin
  456. NewType := ftBlob;
  457. NewSize := 0;
  458. end
  459. else
  460. Result := False;
  461. end;
  462. end;
  463. procedure TConnectionName.AddFieldDefs(cursor: TSQLCursor;
  464. FieldDefs: TfieldDefs);
  465. var
  466. C : TCursorName;
  467. I, TF, FC: Integer;
  468. field: PMYSQL_FIELD;
  469. DFT: TFieldType;
  470. DFS: Integer;
  471. begin
  472. // Writeln('MySQL: Adding fielddefs');
  473. C:=(Cursor as TCursorName);
  474. If (C.FRes=Nil) then
  475. begin
  476. // Writeln('res is nil');
  477. MySQLError(FMySQL,SErrNoQueryResult,Self);
  478. end;
  479. // Writeln('MySQL: have result');
  480. FC:=mysql_num_fields(C.FRes);
  481. SetLength(c.MapDSRowToMSQLRow,FC);
  482. TF := 1;
  483. For I:= 0 to FC-1 do
  484. begin
  485. field := mysql_fetch_field_direct(C.FRES, I);
  486. // Writeln('MySQL: creating fielddef ',I+1);
  487. if MySQLDataType(field^.ftype, field^.length, field^.decimals, DFT, DFS) then
  488. begin
  489. TFieldDef.Create(FieldDefs, FieldDefs.MakeNameUnique(field^.name), DFT, DFS, False, TF);
  490. c.MapDSRowToMSQLRow[TF-1] := I;
  491. inc(TF);
  492. end
  493. end;
  494. // Writeln('MySQL: Finished adding fielddefs');
  495. end;
  496. function TConnectionName.Fetch(cursor: TSQLCursor): boolean;
  497. Var
  498. C : TCursorName;
  499. begin
  500. C:=Cursor as TCursorName;
  501. C.Row:=MySQL_Fetch_row(C.FRes);
  502. Result:=(C.Row<>Nil);
  503. end;
  504. function TConnectionName.LoadField(cursor : TSQLCursor;
  505. FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  506. var
  507. field: PMYSQL_FIELD;
  508. row : MYSQL_ROW;
  509. C : TCursorName;
  510. begin
  511. // Writeln('LoadFieldsFromBuffer');
  512. C:=Cursor as TCursorName;
  513. if C.Row=nil then
  514. begin
  515. // Writeln('LoadFieldsFromBuffer: row=nil');
  516. MySQLError(FMySQL,SErrFetchingData,Self);
  517. end;
  518. Row:=C.Row;
  519. inc(Row,c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]);
  520. field := mysql_fetch_field_direct(C.FRES, c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]);
  521. Result := MySQLWriteData(field^.ftype, field^.length, FieldDef.DataType, Row^, Buffer, CreateBlob);
  522. end;
  523. procedure TConnectionName.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  524. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  525. var
  526. row : MYSQL_ROW;
  527. C : TCursorName;
  528. li : longint;
  529. Lengths : pculong;
  530. begin
  531. C:=Cursor as TCursorName;
  532. if C.Row=nil then
  533. MySQLError(FMySQL,SErrFetchingData,Self);
  534. Row:=C.Row;
  535. inc(Row,c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]);
  536. Lengths := mysql_fetch_lengths(c.FRes);
  537. li := Lengths[c.MapDSRowToMSQLRow[FieldDef.FieldNo-1]];
  538. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  539. Move(pchar(row^)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  540. ABlobBuf^.BlobBuffer^.Size := li;
  541. end;
  542. function InternalStrToFloat(S: string): Extended;
  543. var
  544. I: Integer;
  545. Tmp: string;
  546. begin
  547. Tmp := '';
  548. for I := 1 to Length(S) do
  549. begin
  550. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  551. Tmp := Tmp + DecimalSeparator
  552. else
  553. Tmp := Tmp + S[I];
  554. end;
  555. Result := StrToFloat(Tmp);
  556. end;
  557. function InternalStrToCurrency(S: string): Extended;
  558. var
  559. I: Integer;
  560. Tmp: string;
  561. begin
  562. Tmp := '';
  563. for I := 1 to Length(S) do
  564. begin
  565. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  566. Tmp := Tmp + DecimalSeparator
  567. else
  568. Tmp := Tmp + S[I];
  569. end;
  570. Result := StrToCurr(Tmp);
  571. end;
  572. function InternalStrToDate(S: string): TDateTime;
  573. var
  574. EY, EM, ED: Word;
  575. begin
  576. EY := StrToInt(Copy(S,1,4));
  577. EM := StrToInt(Copy(S,6,2));
  578. ED := StrToInt(Copy(S,9,2));
  579. if (EY = 0) or (EM = 0) or (ED = 0) then
  580. Result:=0
  581. else
  582. Result:=EncodeDate(EY, EM, ED);
  583. end;
  584. function InternalStrToDateTime(S: string): TDateTime;
  585. var
  586. EY, EM, ED: Word;
  587. EH, EN, ES: Word;
  588. begin
  589. EY := StrToInt(Copy(S, 1, 4));
  590. EM := StrToInt(Copy(S, 6, 2));
  591. ED := StrToInt(Copy(S, 9, 2));
  592. EH := StrToInt(Copy(S, 12, 2));
  593. EN := StrToInt(Copy(S, 15, 2));
  594. ES := StrToInt(Copy(S, 18, 2));
  595. if (EY = 0) or (EM = 0) or (ED = 0) then
  596. Result := 0
  597. else
  598. Result := EncodeDate(EY, EM, ED);
  599. Result := Result + EncodeTime(EH, EN, ES, 0);
  600. end;
  601. function InternalStrToTime(S: string): TDateTime;
  602. var
  603. EH, EM, ES: Word;
  604. begin
  605. EH := StrToInt(Copy(S, 1, 2));
  606. EM := StrToInt(Copy(S, 4, 2));
  607. ES := StrToInt(Copy(S, 7, 2));
  608. Result := EncodeTime(EH, EM, ES, 0);
  609. end;
  610. function InternalStrToTimeStamp(S: string): TDateTime;
  611. var
  612. EY, EM, ED: Word;
  613. EH, EN, ES: Word;
  614. begin
  615. {$IFNDEF mysql40}
  616. EY := StrToInt(Copy(S, 1, 4));
  617. EM := StrToInt(Copy(S, 6, 2));
  618. ED := StrToInt(Copy(S, 9, 2));
  619. EH := StrToInt(Copy(S, 12, 2));
  620. EN := StrToInt(Copy(S, 15, 2));
  621. ES := StrToInt(Copy(S, 18, 2));
  622. {$ELSE}
  623. EY := StrToInt(Copy(S, 1, 4));
  624. EM := StrToInt(Copy(S, 5, 2));
  625. ED := StrToInt(Copy(S, 7, 2));
  626. EH := StrToInt(Copy(S, 9, 2));
  627. EN := StrToInt(Copy(S, 11, 2));
  628. ES := StrToInt(Copy(S, 13, 2));
  629. {$ENDIF}
  630. if (EY = 0) or (EM = 0) or (ED = 0) then
  631. Result := 0
  632. else
  633. Result := EncodeDate(EY, EM, ED);
  634. Result := Result + EncodeTime(EH, EN, ES, 0);;
  635. end;
  636. function TConnectionName.MySQLWriteData(AType: enum_field_types;ASize: Integer; AFieldType: TFieldType; Source, Dest: PChar; out CreateBlob : boolean): Boolean;
  637. var
  638. VI: Integer;
  639. VL: LargeInt;
  640. VS: Smallint;
  641. VF: Double;
  642. VC: Currency;
  643. VD: TDateTime;
  644. Src : String;
  645. begin
  646. Result := False;
  647. CreateBlob := False;
  648. if Source = Nil then
  649. exit;
  650. Src:=StrPas(Source);
  651. case AType of
  652. FIELD_TYPE_TINY, FIELD_TYPE_SHORT:
  653. begin
  654. if (Src<>'') then
  655. VS := StrToInt(Src)
  656. else
  657. VS := 0;
  658. Move(VS, Dest^, SizeOf(smallint));
  659. end;
  660. FIELD_TYPE_LONG, FIELD_TYPE_INT24:
  661. begin
  662. if (Src<>'') then
  663. VI := StrToInt(Src)
  664. else
  665. VI := 0;
  666. Move(VI, Dest^, SizeOf(Integer));
  667. end;
  668. FIELD_TYPE_LONGLONG:
  669. begin
  670. if (Src<>'') then
  671. VL := StrToInt64(Src)
  672. else
  673. VL := 0;
  674. Move(VL, Dest^, SizeOf(LargeInt));
  675. end;
  676. {$ifdef mysql50}
  677. FIELD_TYPE_NEWDECIMAL,
  678. {$endif}
  679. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  680. if AFieldType = ftBCD then
  681. begin
  682. VC := InternalStrToCurrency(Src);
  683. Move(VC, Dest^, SizeOf(Currency));
  684. end
  685. else
  686. begin
  687. if Src <> '' then
  688. VF := InternalStrToFloat(Src)
  689. else
  690. VF := 0;
  691. Move(VF, Dest^, SizeOf(Double));
  692. end;
  693. FIELD_TYPE_TIMESTAMP:
  694. begin
  695. if Src <> '' then
  696. VD := InternalStrToTimeStamp(Src)
  697. else
  698. VD := 0;
  699. Move(VD, Dest^, SizeOf(TDateTime));
  700. end;
  701. FIELD_TYPE_DATETIME:
  702. begin
  703. if Src <> '' then
  704. VD := InternalStrToDateTime(Src)
  705. else
  706. VD := 0;
  707. Move(VD, Dest^, SizeOf(TDateTime));
  708. end;
  709. FIELD_TYPE_DATE:
  710. begin
  711. if Src <> '' then
  712. VD := InternalStrToDate(Src)
  713. else
  714. VD := 0;
  715. Move(VD, Dest^, SizeOf(TDateTime));
  716. end;
  717. FIELD_TYPE_TIME:
  718. begin
  719. if Src <> '' then
  720. VD := InternalStrToTime(Src)
  721. else
  722. VD := 0;
  723. Move(VD, Dest^, SizeOf(TDateTime));
  724. end;
  725. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  726. begin
  727. { Write('Moving string of size ',asize,' : ');
  728. P:=Source;
  729. If (P<>nil) then
  730. While P[0]<>#0 do
  731. begin
  732. Write(p[0]);
  733. inc(p);
  734. end;
  735. Writeln;
  736. }
  737. // String-fields which can contain more then dsMaxStringSize characters
  738. // are mapped to ftBlob fields, while their mysql-datatype is FIELD_TYPE_BLOB
  739. if AFieldType in [ftBlob,ftMemo] then
  740. CreateBlob := True
  741. else if Src<> '' then
  742. Move(Source^, Dest^, ASize)
  743. else
  744. Dest^ := #0;
  745. end;
  746. FIELD_TYPE_BLOB:
  747. CreateBlob := True;
  748. end;
  749. Result := True;
  750. end;
  751. procedure TConnectionName.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  752. var qry : TSQLQuery;
  753. begin
  754. if not assigned(Transaction) then
  755. DatabaseError(SErrConnTransactionnSet);
  756. qry := tsqlquery.Create(nil);
  757. qry.transaction := Transaction;
  758. qry.database := Self;
  759. with qry do
  760. begin
  761. ParseSQL := False;
  762. sql.clear;
  763. sql.add('show index from ' + TableName);
  764. open;
  765. end;
  766. while not qry.eof do with IndexDefs.AddIndexDef do
  767. begin
  768. Name := trim(qry.fieldbyname('Key_name').asstring);
  769. Fields := trim(qry.fieldbyname('Column_name').asstring);
  770. If Name = 'PRIMARY' then options := options + [ixPrimary];
  771. If qry.fieldbyname('Non_unique').asinteger = 0 then options := options + [ixUnique];
  772. qry.next;
  773. while (name = trim(qry.fieldbyname('Key_name').asstring)) and (not qry.eof) do
  774. begin
  775. Fields := Fields + ';' + trim(qry.fieldbyname('Column_name').asstring);
  776. qry.next;
  777. end;
  778. end;
  779. qry.close;
  780. qry.free;
  781. end;
  782. function TConnectionName.RowsAffected(cursor: TSQLCursor): TRowsCount;
  783. begin
  784. if assigned(cursor) then
  785. // Compile this without range-checking. RowsAffected can be -1, although
  786. // it's an unsigned integer. (small joke from the mysql-guys)
  787. // Without range-checking this goes ok. If Range is turned on, this results
  788. // in range-check errors.
  789. Result := (cursor as TCursorName).RowsAffected
  790. else
  791. Result := -1;
  792. end;
  793. constructor TConnectionName.Create(AOwner: TComponent);
  794. begin
  795. inherited Create(AOwner);
  796. FConnOptions := FConnOptions + [sqEscapeRepeat] + [sqEscapeSlash];
  797. FMySQL := Nil;
  798. end;
  799. procedure TConnectionName.GetFieldNames(const TableName: string; List: TStrings);
  800. begin
  801. GetDBInfo(stColumns,TableName,'field',List);
  802. end;
  803. procedure TConnectionName.GetTableNames(List: TStrings; SystemTables: Boolean);
  804. begin
  805. GetDBInfo(stTables,'','tables_in_'+DatabaseName,List)
  806. end;
  807. function TConnectionName.GetTransactionHandle(trans: TSQLHandle): pointer;
  808. begin
  809. Result:=Nil;
  810. end;
  811. function TConnectionName.Commit(trans: TSQLHandle): boolean;
  812. begin
  813. // Do nothing.
  814. end;
  815. function TConnectionName.RollBack(trans: TSQLHandle): boolean;
  816. begin
  817. // Do nothing
  818. end;
  819. function TConnectionName.StartdbTransaction(trans: TSQLHandle; AParams : string): boolean;
  820. begin
  821. // Do nothing
  822. end;
  823. procedure TConnectionName.CommitRetaining(trans: TSQLHandle);
  824. begin
  825. // Do nothing
  826. end;
  827. procedure TConnectionName.RollBackRetaining(trans: TSQLHandle);
  828. begin
  829. // Do nothing
  830. end;
  831. function TConnectionName.GetSchemaInfoSQL(SchemaType: TSchemaType;
  832. SchemaObjectName, SchemaPattern: string): string;
  833. begin
  834. case SchemaType of
  835. stTables : result := 'show tables';
  836. stColumns : result := 'show columns from ' + EscapeString(SchemaObjectName);
  837. else
  838. DatabaseError(SMetadataUnavailable)
  839. end; {case}
  840. end;
  841. { TMySQLConnectionDef }
  842. class function TMySQLConnectionDef.TypeName: String;
  843. begin
  844. Result:='MySQL '+MySQLVersion;
  845. end;
  846. class function TMySQLConnectionDef.ConnectionClass: TSQLConnectionClass;
  847. begin
  848. {$IfDef mysql50}
  849. Result:=TMySQL50Connection;
  850. {$ELSE}
  851. {$IfDef mysql41}
  852. Result:=TMySQL41Connection;
  853. {$ELSE}
  854. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  855. Result:=TMySQLConnection;
  856. {$ELSE}
  857. Result:=TMySQL40Connection;
  858. {$EndIf}
  859. {$EndIf}
  860. {$EndIf}
  861. end;
  862. class function TMySQLConnectionDef.Description: String;
  863. begin
  864. Result:='Connect to a MySQL '+MySQLVersion+'database directly via the client library';
  865. end;
  866. {$IfDef mysql50}
  867. initialization
  868. RegisterConnection(TMySQL50ConnectionDef);
  869. finalization
  870. UnRegisterConnection(TMySQL50ConnectionDef);
  871. {$ELSE}
  872. {$IfDef mysql41}
  873. initialization
  874. RegisterConnection(TMySQL41ConnectionDef);
  875. finalization
  876. UnRegisterConnection(TMySQL41ConnectionDef);
  877. {$ELSE}
  878. {$IFDEF mysql4} // temporary backwards compatibility for Lazarus
  879. initialization
  880. RegisterConnection(TMySQL40ConnectionDef);
  881. finalization
  882. UnRegisterConnection(TMySQL40ConnectionDef);
  883. {$ELSE}
  884. initialization
  885. RegisterConnection(TMySQL40ConnectionDef);
  886. finalization
  887. UnRegisterConnection(TMySQL40ConnectionDef);
  888. {$EndIf}
  889. {$EndIf}
  890. {$EndIf}
  891. end.