2
0

mysql4conn.pas 15 KB

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