mysql4conn.pas 15 KB

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