mysql4conn.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 : Int64;
  24. LastInsertID : Int64;
  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. if (HMySQL=Nil) then
  126. New(HMySQL);
  127. mysql_init(HMySQL);
  128. HMySQL:=mysql_real_connect(HMySQL,PChar(H),PChar(U),Pchar(P),Nil,0,Nil,0);
  129. If (HMySQL=Nil) then
  130. MySQlError(Nil,SErrServerConnectFailed,Self);
  131. end;
  132. procedure TMySQLConnection.ConnectToServer;
  133. Var
  134. H,U,P : String;
  135. begin
  136. H:=HostName;
  137. U:=UserName;
  138. P:=Password;
  139. ConnectMySQL(FMySQL,pchar(H),pchar(U),pchar(P));
  140. FServerInfo := strpas(mysql_get_server_info(FMYSQL));
  141. FHostInfo := strpas(mysql_get_host_info(FMYSQL));
  142. end;
  143. procedure TMySQLConnection.SelectDatabase;
  144. begin
  145. if mysql_select_db(FMySQL,pchar(DatabaseName))<>0 then
  146. MySQLError(FMySQL,SErrDatabaseSelectFailed,Self);
  147. end;
  148. procedure TMySQLConnection.DoInternalConnect;
  149. begin
  150. {$IfDef LinkDynamically}
  151. InitialiseMysql4;
  152. {$EndIf}
  153. inherited DoInternalConnect;
  154. ConnectToServer;
  155. SelectDatabase;
  156. end;
  157. procedure TMySQLConnection.DoInternalDisconnect;
  158. begin
  159. inherited DoInternalDisconnect;
  160. mysql_close(FMySQL);
  161. FMySQL:=Nil;
  162. {$IfDef LinkDynamically}
  163. ReleaseMysql4;
  164. {$EndIf}
  165. end;
  166. function TMySQLConnection.GetHandle: pointer;
  167. begin
  168. Result:=FMySQL;
  169. end;
  170. function TMySQLConnection.AllocateCursorHandle: TSQLCursor;
  171. begin
  172. Result:=TMySQLCursor.Create;
  173. end;
  174. function TMySQLConnection.AllocateTransactionHandle: TSQLHandle;
  175. begin
  176. Result:=TMySQLTransaction.Create;
  177. end;
  178. procedure TMySQLConnection.CloseStatement(cursor: TSQLCursor);
  179. Var
  180. C : TMySQLCursor;
  181. begin
  182. C:=Cursor as TMysqlCursor;
  183. if c.FStatementType=stSelect then
  184. c.FNeedData:=False;
  185. If (C.FRes<>Nil) then
  186. begin
  187. C.FRes:=Nil;
  188. end;
  189. if (c.FQMySQL <> Nil) then
  190. begin
  191. mysql_close(c.FQMySQL);
  192. c.FQMySQL:=Nil;
  193. end;
  194. end;
  195. procedure TMySQLConnection.PrepareStatement(cursor: TSQLCursor;
  196. ATransaction: TSQLTransaction; buf: string;AParams : TParams);
  197. begin
  198. if assigned(AParams) and (AParams.count > 0) then
  199. DatabaseError('Parameters (not) yet supported for the MySQL SqlDB connection.',self);
  200. With Cursor as TMysqlCursor do
  201. begin
  202. FStatement:=Buf;
  203. if FStatementType=stSelect then
  204. FNeedData:=True;
  205. ConnectMySQL(FQMySQL,FMySQL^.host,FMySQL^.user,FMySQL^.passwd);
  206. if mysql_select_db(FQMySQL,pchar(DatabaseName))<>0 then
  207. MySQLError(FQMySQL,SErrDatabaseSelectFailed,Self);
  208. end
  209. end;
  210. procedure TMySQLConnection.FreeFldBuffers(cursor: TSQLCursor);
  211. Var
  212. C : TMySQLCursor;
  213. begin
  214. C:=Cursor as TMysqlCursor;
  215. If (C.FRes<>Nil) then
  216. begin
  217. Mysql_free_result(C.FRes);
  218. C.FRes:=Nil;
  219. end;
  220. end;
  221. procedure TMySQLConnection.Execute(cursor: TSQLCursor;
  222. atransaction: tSQLtransaction;AParams : TParams);
  223. Var
  224. C : TMySQLCursor;
  225. begin
  226. C:=Cursor as TMysqlCursor;
  227. If (C.FRes=Nil) then
  228. begin
  229. if mysql_query(c.FQMySQL,Pchar(C.FStatement))<>0 then
  230. MySQLError(c.FQMYSQL,Format(SErrExecuting,[StrPas(mysql_error(c.FQMySQL))]),Self)
  231. else
  232. begin
  233. C.RowsAffected := mysql_affected_rows(c.FQMYSQL);
  234. C.LastInsertID := mysql_insert_id(c.FQMYSQL);
  235. if C.FNeedData then
  236. C.FRes:=mysql_use_result(c.FQMySQL);
  237. end;
  238. end;
  239. end;
  240. function TMySQLConnection.MySQLDataType(AType: enum_field_types; ASize: Integer;
  241. var NewType: TFieldType; var NewSize: Integer): Boolean;
  242. begin
  243. Result := True;
  244. case AType of
  245. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG, FIELD_TYPE_LONGLONG,
  246. FIELD_TYPE_INT24:
  247. begin
  248. NewType := ftInteger;
  249. NewSize := 0;
  250. end;
  251. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  252. begin
  253. NewType := ftFloat;
  254. NewSize := 0;
  255. end;
  256. FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  257. begin
  258. NewType := ftDateTime;
  259. NewSize := 0;
  260. end;
  261. FIELD_TYPE_DATE:
  262. begin
  263. NewType := ftDate;
  264. NewSize := 0;
  265. end;
  266. FIELD_TYPE_TIME:
  267. begin
  268. NewType := ftTime;
  269. NewSize := 0;
  270. end;
  271. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  272. begin
  273. NewType := ftString;
  274. NewSize := ASize;
  275. end;
  276. else
  277. Result := False;
  278. end;
  279. end;
  280. procedure TMySQLConnection.AddFieldDefs(cursor: TSQLCursor;
  281. FieldDefs: TfieldDefs);
  282. var
  283. C : TMySQLCursor;
  284. I, FC: Integer;
  285. field: PMYSQL_FIELD;
  286. DFT: TFieldType;
  287. DFS: Integer;
  288. begin
  289. // Writeln('MySQL: Adding fielddefs');
  290. C:=(Cursor as TMySQLCursor);
  291. If (C.FRes=Nil) then
  292. begin
  293. // Writeln('res is nil');
  294. MySQLError(c.FQMySQL,SErrNoQueryResult,Self);
  295. end;
  296. // Writeln('MySQL: have result');
  297. FC:=mysql_num_fields(C.FRes);
  298. For I:= 0 to FC-1 do
  299. begin
  300. field := mysql_fetch_field_direct(C.FRES, I);
  301. // Writeln('MySQL: creating fielddef ',I+1);
  302. if MySQLDataType(field^.ftype, field^.length, DFT, DFS) then
  303. TFieldDef.Create(FieldDefs, field^.name, DFT, DFS, False, I+1);
  304. end;
  305. // Writeln('MySQL: Finished adding fielddefs');
  306. end;
  307. function TMySQLConnection.Fetch(cursor: TSQLCursor): boolean;
  308. Var
  309. C : TMySQLCursor;
  310. begin
  311. C:=Cursor as TMySQLCursor;
  312. C.Row:=MySQL_Fetch_row(C.FRes);
  313. Result:=(C.Row<>Nil);
  314. end;
  315. function TMySQLConnection.LoadField(cursor : TSQLCursor;
  316. FieldDef : TfieldDef;buffer : pointer) : boolean;
  317. var
  318. I, FC, CT: Integer;
  319. field: PMYSQL_FIELD;
  320. row : TMYSQL_ROW;
  321. C : TMySQLCursor;
  322. begin
  323. // Writeln('LoadFieldsFromBuffer');
  324. C:=Cursor as TMySQLCursor;
  325. if C.Row=nil then
  326. begin
  327. // Writeln('LoadFieldsFromBuffer: row=nil');
  328. MySQLError(c.FQMySQL,SErrFetchingData,Self);
  329. end;
  330. Row:=C.Row;
  331. FC := mysql_num_fields(C.FRES);
  332. for I := 0 to FC-1 do
  333. begin
  334. field := mysql_fetch_field_direct(C.FRES, I);
  335. if field^.name=FieldDef.name then break;
  336. Inc(Row);
  337. end;
  338. CT := MySQLWriteData(field^.ftype, field^.length, Row^, Buffer);
  339. result := true;
  340. end;
  341. function InternalStrToFloat(S: string): Extended;
  342. var
  343. I: Integer;
  344. Tmp: string;
  345. begin
  346. Tmp := '';
  347. for I := 1 to Length(S) do
  348. begin
  349. if not (S[I] in ['0'..'9', '+', '-', 'E', 'e']) then
  350. Tmp := Tmp + DecimalSeparator
  351. else
  352. Tmp := Tmp + S[I];
  353. end;
  354. Result := StrToFloat(Tmp);
  355. end;
  356. function InternalStrToDate(S: string): TDateTime;
  357. var
  358. EY, EM, ED: Word;
  359. begin
  360. EY := StrToInt(Copy(S,1,4));
  361. EM := StrToInt(Copy(S,6,2));
  362. ED := StrToInt(Copy(S,9,2));
  363. if (EY = 0) or (EM = 0) or (ED = 0) then
  364. Result:=0
  365. else
  366. Result:=EncodeDate(EY, EM, ED);
  367. end;
  368. function InternalStrToDateTime(S: string): TDateTime;
  369. var
  370. EY, EM, ED: Word;
  371. EH, EN, ES: Word;
  372. begin
  373. EY := StrToInt(Copy(S, 1, 4));
  374. EM := StrToInt(Copy(S, 6, 2));
  375. ED := StrToInt(Copy(S, 9, 2));
  376. EH := StrToInt(Copy(S, 11, 2));
  377. EN := StrToInt(Copy(S, 14, 2));
  378. ES := StrToInt(Copy(S, 17, 2));
  379. if (EY = 0) or (EM = 0) or (ED = 0) then
  380. Result := 0
  381. else
  382. Result := EncodeDate(EY, EM, ED);
  383. Result := Result + EncodeTime(EH, EN, ES, 0);
  384. end;
  385. function InternalStrToTime(S: string): TDateTime;
  386. var
  387. EH, EM, ES: Word;
  388. begin
  389. EH := StrToInt(Copy(S, 1, 2));
  390. EM := StrToInt(Copy(S, 4, 2));
  391. ES := StrToInt(Copy(S, 7, 2));
  392. Result := EncodeTime(EH, EM, ES, 0);
  393. end;
  394. function InternalStrToTimeStamp(S: string): TDateTime;
  395. var
  396. EY, EM, ED: Word;
  397. EH, EN, ES: Word;
  398. begin
  399. EY := StrToInt(Copy(S, 1, 4));
  400. EM := StrToInt(Copy(S, 5, 2));
  401. ED := StrToInt(Copy(S, 7, 2));
  402. EH := StrToInt(Copy(S, 9, 2));
  403. EN := StrToInt(Copy(S, 11, 2));
  404. ES := StrToInt(Copy(S, 13, 2));
  405. if (EY = 0) or (EM = 0) or (ED = 0) then
  406. Result := 0
  407. else
  408. Result := EncodeDate(EY, EM, ED);
  409. Result := Result + EncodeTime(EH, EN, ES, 0);;
  410. end;
  411. function TMySQLConnection.MySQLWriteData(AType: enum_field_types;ASize: Integer; Source, Dest: PChar): Integer;
  412. var
  413. VI: Integer;
  414. VF: Double;
  415. VD: TDateTime;
  416. Src : String;
  417. begin
  418. Result := 0;
  419. If (Source<>Nil) Then
  420. Src:=StrPas(Source)
  421. else
  422. Src:='';
  423. case AType of
  424. FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG, FIELD_TYPE_LONGLONG,
  425. FIELD_TYPE_INT24:
  426. begin
  427. Result:=SizeOf(Integer);
  428. if (Src<>'') then
  429. VI := StrToInt(Src)
  430. else
  431. VI := 0;
  432. Move(VI, Dest^, Result);
  433. end;
  434. FIELD_TYPE_DECIMAL, FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE:
  435. begin
  436. Result := SizeOf(Double);
  437. if Src <> '' then
  438. VF := InternalStrToFloat(Src)
  439. else
  440. VF := 0;
  441. Move(VF, Dest^, Result);
  442. end;
  443. FIELD_TYPE_TIMESTAMP:
  444. begin
  445. Result := SizeOf(TDateTime);
  446. if Src <> '' then
  447. VD := InternalStrToTimeStamp(Src)
  448. else
  449. VD := 0;
  450. Move(VD, Dest^, Result);
  451. end;
  452. FIELD_TYPE_DATETIME:
  453. begin
  454. Result := SizeOf(TDateTime);
  455. if Src <> '' then
  456. VD := InternalStrToDateTime(Src)
  457. else
  458. VD := 0;
  459. Move(VD, Dest^, Result);
  460. end;
  461. FIELD_TYPE_DATE:
  462. begin
  463. Result := SizeOf(TDateTime);
  464. if Src <> '' then
  465. VD := InternalStrToDate(Src)
  466. else
  467. VD := 0;
  468. Move(VD, Dest^, Result);
  469. end;
  470. FIELD_TYPE_TIME:
  471. begin
  472. Result := SizeOf(TDateTime);
  473. if Src <> '' then
  474. VD := InternalStrToTime(Src)
  475. else
  476. VD := 0;
  477. Move(VD, Dest^, Result);
  478. end;
  479. FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING, FIELD_TYPE_ENUM, FIELD_TYPE_SET:
  480. begin
  481. Result := ASize;
  482. { Write('Moving string of size ',asize,' : ');
  483. P:=Source;
  484. If (P<>nil) then
  485. While P[0]<>#0 do
  486. begin
  487. Write(p[0]);
  488. inc(p);
  489. end;
  490. Writeln;
  491. } if Src<> '' then
  492. Move(Source^, Dest^, Result)
  493. else
  494. Dest^ := #0;
  495. end;
  496. end;
  497. end;
  498. procedure TMySQLConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  499. var qry : TSQLQuery;
  500. begin
  501. if not assigned(Transaction) then
  502. DatabaseError(SErrConnTransactionnSet);
  503. qry := tsqlquery.Create(nil);
  504. qry.transaction := Transaction;
  505. qry.database := Self;
  506. with qry do
  507. begin
  508. ReadOnly := True;
  509. sql.clear;
  510. sql.add('show index from ' + TableName);
  511. open;
  512. end;
  513. while not qry.eof do with IndexDefs.AddIndexDef do
  514. begin
  515. Name := trim(qry.fieldbyname('Key_name').asstring);
  516. Fields := trim(qry.fieldbyname('Column_name').asstring);
  517. If Name = 'PRIMARY' then options := options + [ixPrimary];
  518. If qry.fieldbyname('Non_unique').asinteger = 0 then options := options + [ixUnique];
  519. qry.next;
  520. { while (name = qry.fields[0].asstring) and (not qry.eof) do
  521. begin
  522. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  523. qry.next;
  524. end;}
  525. end;
  526. qry.close;
  527. qry.free;
  528. end;
  529. function TMySQLConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  530. begin
  531. Result:=Nil;
  532. end;
  533. function TMySQLConnection.Commit(trans: TSQLHandle): boolean;
  534. begin
  535. // Do nothing.
  536. end;
  537. function TMySQLConnection.RollBack(trans: TSQLHandle): boolean;
  538. begin
  539. // Do nothing
  540. end;
  541. function TMySQLConnection.StartdbTransaction(trans: TSQLHandle): boolean;
  542. begin
  543. // Do nothing
  544. end;
  545. procedure TMySQLConnection.CommitRetaining(trans: TSQLHandle);
  546. begin
  547. // Do nothing
  548. end;
  549. procedure TMySQLConnection.RollBackRetaining(trans: TSQLHandle);
  550. begin
  551. // Do nothing
  552. end;
  553. end.