mysql4conn.pas 15 KB

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