mysql4conn.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. unit mysql4conn;
  2. {$mode objfpc}{$H+}
  3. {$Define LinkDynamically}
  4. interface
  5. uses
  6. Classes, SysUtils,sqldb,db,
  7. {$IfDef LinkDynamically}
  8. mysql4dyn,mysql4_comdyn;
  9. {$Else}
  10. mysql4,mysql4_com;
  11. {$EndIf}
  12. Type
  13. TMySQLTransaction = Class(TSQLHandle)
  14. protected
  15. end;
  16. TMySQLCursor = Class(TSQLCursor)
  17. protected
  18. FQMySQL : PMySQL;
  19. FRes: PMYSQL_RES; { Record pointer }
  20. FNeedData : Boolean;
  21. FStatement : String;
  22. Row : TMYSQL_ROW;
  23. RowsAffected : QWord;
  24. LastInsertID : QWord;
  25. end;
  26. TMySQLConnection = class (TSQLConnection)
  27. private
  28. FDialect: integer;
  29. FHostInfo: String;
  30. FServerInfo: String;
  31. FMySQL : PMySQL;
  32. function GetClientInfo: string;
  33. function GetServerStatus: String;
  34. procedure ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  35. protected
  36. function StrToStatementType(s : string) : TStatementType; override;
  37. Procedure ConnectToServer; virtual;
  38. Procedure SelectDatabase; virtual;
  39. function MySQLDataType(AType: enum_field_types; ASize: Integer; var NewType: TFieldType; var NewSize: Integer): Boolean;
  40. function MySQLWriteData(AType: enum_field_types; ASize: Integer; Source, Dest: PChar): Integer;
  41. // SQLConnection methods
  42. procedure DoInternalConnect; override;
  43. procedure DoInternalDisconnect; override;
  44. function GetHandle : pointer; override;
  45. Function AllocateCursorHandle : TSQLCursor; override;
  46. Function AllocateTransactionHandle : TSQLHandle; override;
  47. procedure CloseStatement(cursor : TSQLCursor); override;
  48. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  49. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  50. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams); override;
  51. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  52. function Fetch(cursor : TSQLCursor) : boolean; override;
  53. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer) : boolean; override;
  54. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  55. function Commit(trans : TSQLHandle) : boolean; override;
  56. function RollBack(trans : TSQLHandle) : boolean; override;
  57. function StartdbTransaction(trans : TSQLHandle) : boolean; override;
  58. procedure CommitRetaining(trans : TSQLHandle); override;
  59. procedure RollBackRetaining(trans : TSQLHandle); override;
  60. procedure UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string); override;
  61. Public
  62. Property ServerInfo : String Read FServerInfo;
  63. Property HostInfo : String Read FHostInfo;
  64. property ClientInfo: string read GetClientInfo;
  65. property ServerStatus : String read GetServerStatus;
  66. published
  67. property Dialect : integer read FDialect write FDialect;
  68. property DatabaseName;
  69. property HostName;
  70. property KeepConnection;
  71. property LoginPrompt;
  72. property Params;
  73. property OnLogin;
  74. end;
  75. EMySQLError = Class(Exception);
  76. implementation
  77. uses dbconst;
  78. { TMySQLConnection }
  79. Resourcestring
  80. SErrServerConnectFailed = 'Server connect failed.';
  81. SErrDatabaseSelectFailed = 'failed to select database: %s';
  82. SErrDatabaseCreate = 'Failed to create database: %s';
  83. SErrDatabaseDrop = 'Failed to drop database: %s';
  84. SErrNoData = 'No data for record';
  85. SErrExecuting = 'Error executing query: %s';
  86. SErrFetchingdata = 'Error fetching row data: %s';
  87. SErrGettingResult = 'Error getting result set: %s';
  88. SErrNoQueryResult = 'No result from query.';
  89. Procedure MySQlError(R : PMySQL;Msg: String;Comp : TComponent);
  90. Var
  91. MySQLMsg : String;
  92. begin
  93. If (R<>Nil) then
  94. begin
  95. MySQLMsg:=Strpas(mysql_error(R));
  96. DatabaseErrorFmt(Msg,[MySQLMsg],Comp);
  97. end
  98. else
  99. DatabaseError(Msg,Comp);
  100. end;
  101. function TMySQLConnection.StrToStatementType(s : string) : TStatementType;
  102. begin
  103. S:=Lowercase(s);
  104. if s = 'show' then exit(stSelect);
  105. result := inherited StrToStatementType(s);
  106. end;
  107. function TMySQLConnection.GetClientInfo: string;
  108. begin
  109. {$IfDef LinkDynamically}
  110. // To make it possible to call this if there's no connection yet
  111. InitialiseMysql4;
  112. {$EndIf}
  113. Result:=strpas(mysql_get_client_info());
  114. {$IfDef LinkDynamically}
  115. ReleaseMysql4;
  116. {$EndIf}
  117. end;
  118. function TMySQLConnection.GetServerStatus: String;
  119. begin
  120. CheckConnected;
  121. Result := mysql_stat(FMYSQL);
  122. end;
  123. procedure TMySQLConnection.ConnectMySQL(var HMySQL : PMySQL;H,U,P : pchar);
  124. begin
  125. HMySQL := mysql_init(HMySQL);
  126. HMySQL:=mysql_real_connect(HMySQL,PChar(H),PChar(U),Pchar(P),Nil,0,Nil,0);
  127. If (HMySQL=Nil) then
  128. MySQlError(Nil,SErrServerConnectFailed,Self);
  129. end;
  130. procedure TMySQLConnection.ConnectToServer;
  131. Var
  132. H,U,P : String;
  133. begin
  134. H:=HostName;
  135. U:=UserName;
  136. P:=Password;
  137. ConnectMySQL(FMySQL,pchar(H),pchar(U),pchar(P));
  138. FServerInfo := strpas(mysql_get_server_info(FMYSQL));
  139. FHostInfo := strpas(mysql_get_host_info(FMYSQL));
  140. end;
  141. procedure TMySQLConnection.SelectDatabase;
  142. begin
  143. if mysql_select_db(FMySQL,pchar(DatabaseName))<>0 then
  144. MySQLError(FMySQL,SErrDatabaseSelectFailed,Self);
  145. end;
  146. procedure TMySQLConnection.DoInternalConnect;
  147. begin
  148. {$IfDef LinkDynamically}
  149. InitialiseMysql4;
  150. {$EndIf}
  151. inherited DoInternalConnect;
  152. ConnectToServer;
  153. SelectDatabase;
  154. end;
  155. procedure TMySQLConnection.DoInternalDisconnect;
  156. begin
  157. inherited DoInternalDisconnect;
  158. mysql_close(FMySQL);
  159. FMySQL:=Nil;
  160. {$IfDef LinkDynamically}
  161. ReleaseMysql4;
  162. {$EndIf}
  163. end;
  164. function TMySQLConnection.GetHandle: pointer;
  165. begin
  166. Result:=FMySQL;
  167. end;
  168. function TMySQLConnection.AllocateCursorHandle: TSQLCursor;
  169. begin
  170. Result:=TMySQLCursor.Create;
  171. end;
  172. function TMySQLConnection.AllocateTransactionHandle: TSQLHandle;
  173. begin
  174. Result:=TMySQLTransaction.Create;
  175. end;
  176. procedure TMySQLConnection.CloseStatement(cursor: TSQLCursor);
  177. Var
  178. C : TMySQLCursor;
  179. begin
  180. C:=Cursor as TMysqlCursor;
  181. if c.FStatementType=stSelect then
  182. c.FNeedData:=False;
  183. If (C.FRes<>Nil) then
  184. begin
  185. C.FRes:=Nil;
  186. end;
  187. if (c.FQMySQL <> Nil) then
  188. begin
  189. mysql_close(c.FQMySQL);
  190. c.FQMySQL:=Nil;
  191. end;
  192. end;
  193. procedure TMySQLConnection.PrepareStatement(cursor: TSQLCursor;
  194. ATransaction: TSQLTransaction; buf: string;AParams : TParams);
  195. begin
  196. if assigned(AParams) and (AParams.count > 0) then
  197. DatabaseError('Parameters (not) yet supported for the MySQL SqlDB connection.',self);
  198. ObtainSQLStatementType(cursor,buf);
  199. With Cursor as TMysqlCursor do
  200. begin
  201. FStatement:=Buf;
  202. if FStatementType=stSelect then
  203. FNeedData:=True;
  204. ConnectMySQL(FQMySQL,FMySQL^.host,FMySQL^.user,FMySQL^.passwd);
  205. if mysql_select_db(FQMySQL,pchar(DatabaseName))<>0 then
  206. MySQLError(FQMySQL,SErrDatabaseSelectFailed,Self);
  207. end
  208. end;
  209. procedure TMySQLConnection.FreeFldBuffers(cursor: TSQLCursor);
  210. Var
  211. C : TMySQLCursor;
  212. begin
  213. C:=Cursor as TMysqlCursor;
  214. If (C.FRes<>Nil) then
  215. begin
  216. Mysql_free_result(C.FRes);
  217. C.FRes:=Nil;
  218. end;
  219. end;
  220. procedure TMySQLConnection.Execute(cursor: TSQLCursor;
  221. atransaction: tSQLtransaction;AParams : TParams);
  222. Var
  223. C : TMySQLCursor;
  224. begin
  225. C:=Cursor as TMysqlCursor;
  226. If (C.FRes=Nil) then
  227. begin
  228. if mysql_query(c.FQMySQL,Pchar(C.FStatement))<>0 then
  229. MySQLError(c.FQMYSQL,Format(SErrExecuting,[StrPas(mysql_error(c.FQMySQL))]),Self)
  230. else
  231. begin
  232. C.RowsAffected := mysql_affected_rows(c.FQMYSQL);
  233. C.LastInsertID := mysql_insert_id(c.FQMYSQL);
  234. if C.FNeedData then
  235. C.FRes:=mysql_use_result(c.FQMySQL);
  236. end;
  237. end;
  238. end;
  239. function TMySQLConnection.MySQLDataType(AType: enum_field_types; ASize: Integer;
  240. var NewType: TFieldType; var NewSize: Integer): Boolean;
  241. begin
  242. Result := True;
  243. case AType of
  244. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG, FIELD_TYPE_LONGLONG,
  245. FIELD_TYPE_INT24:
  246. begin
  247. NewType := ftInteger;
  248. NewSize := 0;
  249. end;
  250. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  251. begin
  252. NewType := ftFloat;
  253. NewSize := 0;
  254. end;
  255. FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  256. begin
  257. NewType := ftDateTime;
  258. NewSize := 0;
  259. end;
  260. FIELD_TYPE_DATE:
  261. begin
  262. NewType := ftDate;
  263. NewSize := 0;
  264. end;
  265. FIELD_TYPE_TIME:
  266. begin
  267. NewType := ftTime;
  268. NewSize := 0;
  269. end;
  270. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  271. begin
  272. NewType := ftString;
  273. NewSize := ASize;
  274. end;
  275. else
  276. Result := False;
  277. end;
  278. end;
  279. procedure TMySQLConnection.AddFieldDefs(cursor: TSQLCursor;
  280. FieldDefs: TfieldDefs);
  281. var
  282. C : TMySQLCursor;
  283. I, FC: Integer;
  284. field: PMYSQL_FIELD;
  285. DFT: TFieldType;
  286. DFS: Integer;
  287. begin
  288. // Writeln('MySQL: Adding fielddefs');
  289. C:=(Cursor as TMySQLCursor);
  290. If (C.FRes=Nil) then
  291. begin
  292. // Writeln('res is nil');
  293. MySQLError(c.FQMySQL,SErrNoQueryResult,Self);
  294. end;
  295. // Writeln('MySQL: have result');
  296. FC:=mysql_num_fields(C.FRes);
  297. For I:= 0 to FC-1 do
  298. begin
  299. field := mysql_fetch_field_direct(C.FRES, I);
  300. // Writeln('MySQL: creating fielddef ',I+1);
  301. if MySQLDataType(field^.ftype, field^.length, DFT, DFS) then
  302. TFieldDef.Create(FieldDefs, field^.name, DFT, DFS, False, I+1);
  303. end;
  304. // Writeln('MySQL: Finished adding fielddefs');
  305. end;
  306. function TMySQLConnection.Fetch(cursor: TSQLCursor): boolean;
  307. Var
  308. C : TMySQLCursor;
  309. begin
  310. C:=Cursor as TMySQLCursor;
  311. C.Row:=MySQL_Fetch_row(C.FRes);
  312. Result:=(C.Row<>Nil);
  313. end;
  314. function TMySQLConnection.LoadField(cursor : TSQLCursor;
  315. FieldDef : TfieldDef;buffer : pointer) : boolean;
  316. var
  317. I, FC, CT: Integer;
  318. field: PMYSQL_FIELD;
  319. row : TMYSQL_ROW;
  320. C : TMySQLCursor;
  321. begin
  322. // Writeln('LoadFieldsFromBuffer');
  323. C:=Cursor as TMySQLCursor;
  324. if C.Row=nil then
  325. begin
  326. // Writeln('LoadFieldsFromBuffer: row=nil');
  327. MySQLError(c.FQMySQL,SErrFetchingData,Self);
  328. end;
  329. Row:=C.Row;
  330. FC := mysql_num_fields(C.FRES);
  331. for I := 0 to FC-1 do
  332. begin
  333. field := mysql_fetch_field_direct(C.FRES, I);
  334. if field^.name=FieldDef.name then break;
  335. Inc(Row);
  336. end;
  337. CT := MySQLWriteData(field^.ftype, field^.length, Row^, Buffer);
  338. result := true;
  339. end;
  340. function InternalStrToFloat(S: string): Extended;
  341. var
  342. I: Integer;
  343. Tmp: string;
  344. begin
  345. Tmp := '';
  346. for I := 1 to Length(S) do
  347. begin
  348. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  349. Tmp := Tmp + DecimalSeparator
  350. else
  351. Tmp := Tmp + S[I];
  352. end;
  353. Result := StrToFloat(Tmp);
  354. end;
  355. function InternalStrToDate(S: string): TDateTime;
  356. var
  357. EY, EM, ED: Word;
  358. begin
  359. EY := StrToInt(Copy(S,1,4));
  360. EM := StrToInt(Copy(S,6,2));
  361. ED := StrToInt(Copy(S,9,2));
  362. if (EY = 0) or (EM = 0) or (ED = 0) then
  363. Result:=0
  364. else
  365. Result:=EncodeDate(EY, EM, ED);
  366. end;
  367. function InternalStrToDateTime(S: string): TDateTime;
  368. var
  369. EY, EM, ED: Word;
  370. EH, EN, ES: Word;
  371. begin
  372. EY := StrToInt(Copy(S, 1, 4));
  373. EM := StrToInt(Copy(S, 6, 2));
  374. ED := StrToInt(Copy(S, 9, 2));
  375. EH := StrToInt(Copy(S, 11, 2));
  376. EN := StrToInt(Copy(S, 14, 2));
  377. ES := StrToInt(Copy(S, 17, 2));
  378. if (EY = 0) or (EM = 0) or (ED = 0) then
  379. Result := 0
  380. else
  381. Result := EncodeDate(EY, EM, ED);
  382. Result := Result + EncodeTime(EH, EN, ES, 0);
  383. end;
  384. function InternalStrToTime(S: string): TDateTime;
  385. var
  386. EH, EM, ES: Word;
  387. begin
  388. EH := StrToInt(Copy(S, 1, 2));
  389. EM := StrToInt(Copy(S, 4, 2));
  390. ES := StrToInt(Copy(S, 7, 2));
  391. Result := EncodeTime(EH, EM, ES, 0);
  392. end;
  393. function InternalStrToTimeStamp(S: string): TDateTime;
  394. var
  395. EY, EM, ED: Word;
  396. EH, EN, ES: Word;
  397. begin
  398. EY := StrToInt(Copy(S, 1, 4));
  399. EM := StrToInt(Copy(S, 5, 2));
  400. ED := StrToInt(Copy(S, 7, 2));
  401. EH := StrToInt(Copy(S, 9, 2));
  402. EN := StrToInt(Copy(S, 11, 2));
  403. ES := StrToInt(Copy(S, 13, 2));
  404. if (EY = 0) or (EM = 0) or (ED = 0) then
  405. Result := 0
  406. else
  407. Result := EncodeDate(EY, EM, ED);
  408. Result := Result + EncodeTime(EH, EN, ES, 0);;
  409. end;
  410. function TMySQLConnection.MySQLWriteData(AType: enum_field_types;ASize: Integer; Source, Dest: PChar): Integer;
  411. var
  412. VI: Integer;
  413. VF: Double;
  414. VD: TDateTime;
  415. Src : String;
  416. begin
  417. Result := 0;
  418. If (Source<>Nil) Then
  419. Src:=StrPas(Source)
  420. else
  421. Src:='';
  422. case AType of
  423. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG, FIELD_TYPE_LONGLONG,
  424. FIELD_TYPE_INT24:
  425. begin
  426. Result:=SizeOf(Integer);
  427. if (Src<>'') then
  428. VI := StrToInt(Src)
  429. else
  430. VI := 0;
  431. Move(VI, Dest^, Result);
  432. end;
  433. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  434. begin
  435. Result := SizeOf(Double);
  436. if Src <> '' then
  437. VF := InternalStrToFloat(Src)
  438. else
  439. VF := 0;
  440. Move(VF, Dest^, Result);
  441. end;
  442. FIELD_TYPE_TIMESTAMP:
  443. begin
  444. Result := SizeOf(TDateTime);
  445. if Src <> '' then
  446. VD := InternalStrToTimeStamp(Src)
  447. else
  448. VD := 0;
  449. Move(VD, Dest^, Result);
  450. end;
  451. FIELD_TYPE_DATETIME:
  452. begin
  453. Result := SizeOf(TDateTime);
  454. if Src <> '' then
  455. VD := InternalStrToDateTime(Src)
  456. else
  457. VD := 0;
  458. Move(VD, Dest^, Result);
  459. end;
  460. FIELD_TYPE_DATE:
  461. begin
  462. Result := SizeOf(TDateTime);
  463. if Src <> '' then
  464. VD := InternalStrToDate(Src)
  465. else
  466. VD := 0;
  467. Move(VD, Dest^, Result);
  468. end;
  469. FIELD_TYPE_TIME:
  470. begin
  471. Result := SizeOf(TDateTime);
  472. if Src <> '' then
  473. VD := InternalStrToTime(Src)
  474. else
  475. VD := 0;
  476. Move(VD, Dest^, Result);
  477. end;
  478. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  479. begin
  480. Result := ASize;
  481. { Write('Moving string of size ',asize,' : ');
  482. P:=Source;
  483. If (P<>nil) then
  484. While P[0]<>#0 do
  485. begin
  486. Write(p[0]);
  487. inc(p);
  488. end;
  489. Writeln;
  490. } if Src<> '' then
  491. Move(Source^, Dest^, Result)
  492. else
  493. Dest^ := #0;
  494. end;
  495. end;
  496. end;
  497. procedure TMySQLConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  498. var qry : TSQLQuery;
  499. begin
  500. if not assigned(Transaction) then
  501. DatabaseError(SErrConnTransactionnSet);
  502. qry := tsqlquery.Create(nil);
  503. qry.transaction := Transaction;
  504. qry.database := Self;
  505. with qry do
  506. begin
  507. ReadOnly := True;
  508. sql.clear;
  509. sql.add('show index from ' + TableName);
  510. open;
  511. end;
  512. while not qry.eof do with IndexDefs.AddIndexDef do
  513. begin
  514. Name := trim(qry.fieldbyname('Key_name').asstring);
  515. Fields := trim(qry.fieldbyname('Column_name').asstring);
  516. If Name = 'PRIMARY' then options := options + [ixPrimary];
  517. If qry.fieldbyname('Non_unique').asinteger = 0 then options := options + [ixUnique];
  518. qry.next;
  519. { while (name = qry.fields[0].asstring) and (not qry.eof) do
  520. begin
  521. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  522. qry.next;
  523. end;}
  524. end;
  525. qry.close;
  526. qry.free;
  527. end;
  528. function TMySQLConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  529. begin
  530. Result:=Nil;
  531. end;
  532. function TMySQLConnection.Commit(trans: TSQLHandle): boolean;
  533. begin
  534. // Do nothing.
  535. end;
  536. function TMySQLConnection.RollBack(trans: TSQLHandle): boolean;
  537. begin
  538. // Do nothing
  539. end;
  540. function TMySQLConnection.StartdbTransaction(trans: TSQLHandle): boolean;
  541. begin
  542. // Do nothing
  543. end;
  544. procedure TMySQLConnection.CommitRetaining(trans: TSQLHandle);
  545. begin
  546. // Do nothing
  547. end;
  548. procedure TMySQLConnection.RollBackRetaining(trans: TSQLHandle);
  549. begin
  550. // Do nothing
  551. end;
  552. end.