source: trunk/Demo/Packages/CoolWeb/Persistence/USqlDatabase.pas

Last change on this file was 60, checked in by chronos, 12 years ago
File size: 13.9 KB
Line 
1unit USqlDatabase;
2
3{$mode Delphi}{$H+}
4
5// Modified: 2010-12-24
6
7interface
8
9uses
10 SysUtils, Classes, Dialogs, mysql50, TypInfo,
11 SpecializedDictionary, SpecializedList;
12
13type
14 EQueryError = class(Exception);
15
16 TClientCapabilities = (_CLIENT_LONG_PASSWORD, _CLIENT_FOUND_ROWS,
17 _CLIENT_LONG_FLAG, _CLIENT_CONNECT_WITH_DB, _CLIENT_NO_SCHEMA,
18 _CLIENT_COMPRESS, _CLIENT_ODBC, _CLIENT_LOCAL_FILES, _CLIENT_IGNORE_SPACE,
19 _CLIENT_INTERACTIVE, _CLIENT_SSL, _CLIENT_IGNORE_SIGPIPE, _CLIENT_TRANSACTIONS);
20
21 TSetClientCapabilities = set of TClientCapabilities;
22
23 TLogEvent = procedure(Sender: TObject; Text: string) of object;
24
25 TDbRows = class(TListObject)
26 private
27 function GetData(Index: Integer): TDictionaryStringString;
28 procedure SetData(Index: Integer; const Value: TDictionaryStringString);
29 public
30 property Data[Index: Integer]: TDictionaryStringString read GetData write SetData; default;
31 destructor Destroy; override;
32 end;
33
34 { TSqlDatabase }
35
36 TSqlDatabase = class(TComponent)
37 private
38 FEncoding: string;
39 FHostName: string;
40 FPassword: string;
41 FPort: Word;
42 FSession: PMYSQL;
43 FConnected: Boolean;
44 FDatabase: string;
45 FUserName: string;
46 FOnLogQuery: TLogEvent;
47 procedure mySQLClient1ConnectError(Sender: TObject; Msg: String);
48 function GetConnected: Boolean;
49 function GetLastErrorMessage: string;
50 function GetLastErrorNumber: Integer;
51 function GetCharset: string;
52 procedure SetConnected(const AValue: Boolean);
53 procedure SetDatabase(const Value: string);
54 public
55 LastUsedTable: string;
56 LastQuery: string;
57 procedure CreateDatabase;
58 procedure CreateTable(Name: string);
59 procedure CreateColumn(Table, ColumnName: string; ColumnType: TTypeKind);
60 procedure Query(DbRows: TDbRows; Data: string);
61 procedure Select(DbRows: TDbRows; ATable: string; Filter: string = '*'; Condition: string = '1');
62 procedure Delete(ATable: string; Condition: string = '1';
63 Schema: string = '');
64 procedure Insert(ATable: string; Data: TDictionaryStringString;
65 Schema: string = '');
66 procedure Update(ATable: string; Data: TDictionaryStringString;
67 Condition: string = '1'; Schema: string = '');
68 procedure Replace(ATable: string; Data: TDictionaryStringString;
69 Schema: string = '');
70 procedure Connect;
71 procedure Disconnect;
72 function LastInsertId: Integer;
73 property LastErrorMessage: string read GetLastErrorMessage;
74 property LastErrorNumber: Integer read GetLastErrorNumber;
75 constructor Create(AOwner: TComponent); override;
76 destructor Destroy; override;
77 property Charset: string read GetCharset;
78 published
79 property Connected: Boolean read GetConnected write SetConnected;
80 property Database: string read FDatabase write SetDatabase;
81 property HostName: string read FHostName write FHostName;
82 property UserName: string read FUserName write FUserName;
83 property Password: string read FPassword write FPassword;
84 property Port: Word read FPort write FPort;
85 property Encoding: string read FEncoding write FEncoding;
86 property OnLogQuery: TLogEvent read FOnLogQuery write FOnLogQuery;
87 end;
88
89 function MySQLFloatToStr(F: Real): string;
90 function MySQLStrToFloat(S: string): Real;
91 function SQLToDateTime(Value: string): TDateTime;
92 function SQLToTime(Value: string): TDateTime;
93 function SQLToDate(Value: string): TDateTime;
94 function DateTimeToSQL(Value: TDateTime): string;
95 function TimeToSQL(Value: TDateTime): string;
96 function DateToSQL(Value: TDateTime): string;
97
98procedure Register;
99
100
101implementation
102
103uses
104 DateUtils, Math;
105
106resourcestring
107 SDatabaseQueryError = 'Database query error: "%s"';
108
109const
110 CLIENT_LONG_PASSWORD = 1; // new more secure passwords
111 CLIENT_FOUND_ROWS = 2; // Found instead of affected rows
112 CLIENT_LONG_FLAG = 4; // Get all column flags
113 CLIENT_CONNECT_WITH_DB = 8; // One can specify db on connect
114 CLIENT_NO_SCHEMA = 16; // Don't allow database.table.column
115 CLIENT_COMPRESS = 32; // Can use compression protcol
116 CLIENT_ODBC = 64; // Odbc client
117 CLIENT_LOCAL_FILES = 128; // Can use LOAD DATA LOCAL
118 CLIENT_IGNORE_SPACE = 256; // Ignore spaces before '('
119 CLIENT_INTERACTIVE = 1024; // This is an interactive client
120 CLIENT_SSL = 2048; // Switch to SSL after handshake
121 CLIENT_IGNORE_SIGPIPE = 4096; // IGNORE sigpipes
122 CLIENT_TRANSACTIONS = 8192; // Client knows about transactions
123
124procedure Register;
125begin
126 RegisterComponents('CoolWeb', [TSqlDatabase]);
127end;
128
129function MySQLFloatToStr(F: Real): string;
130var
131 S: string;
132begin
133 S := FloatToStr(F);
134 if Pos(',', S) > 0 then S[Pos(',', S)] := '.';
135 Result := S;
136end;
137
138function MySQLStrToFloat(S: string): Real;
139begin
140 if Pos('.', S) > 0 then S[Pos('.', S)] := ',';
141 Result := StrToFloat(S);
142end;
143
144function StrToStr(Value: string): string;
145begin
146 Result := Value;
147end;
148
149function SQLToDateTime(Value: string): TDateTime;
150var
151 Parts: TListString;
152 DateParts: TListString;
153 TimeParts: TListString;
154begin
155 try
156 Parts := TListString.Create;
157 DateParts := TListString.Create;
158 TimeParts := TListString.Create;
159
160 Parts.Explode(Value, ' ', StrToStr);
161 DateParts.Explode(Parts[0], '-', StrToStr);
162 Result := EncodeDate(StrToInt(DateParts[0]), StrToInt(DateParts[1]),
163 StrToInt(DateParts[2]));
164 if Parts.Count > 1 then begin
165 TimeParts.Explode(Parts[1], ':', StrToStr);
166 Result := Result + EncodeTime(StrToInt(TimeParts[0]), StrToInt(TimeParts[1]),
167 StrToInt(TimeParts[2]), 0);
168 end;
169 finally
170 DateParts.Free;
171 TimeParts.Free;
172 Parts.Free;
173 end;
174end;
175
176function SQLToDate(Value: string): TDateTime;
177var
178 DateParts: TListString;
179 Date: TDateTime;
180begin
181 try
182 DateParts := TListString.Create;
183 DateParts.Explode(Value, '-', StrToStr);
184 if TryEncodeDate(StrToInt(DateParts[0]), StrToInt(DateParts[1]),
185 StrToInt(DateParts[2]), Date) then
186 Result := Date else Result := 0;
187 finally
188 DateParts.Free;
189 end;
190end;
191
192function DateTimeToSQL(Value: TDateTime): string;
193begin
194 Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', Value);
195end;
196
197function TimeToSQL(Value: TDateTime): string;
198begin
199 Result := FormatDateTime('hh:nn:ss', Value);
200end;
201
202function DateToSQL(Value: TDateTime): string;
203begin
204 Result := FormatDateTime('yyyy-mm-dd', Value);
205end;
206
207function SQLToTime(Value: string): TDateTime;
208var
209 TimeParts: TListString;
210 Time: TDateTime;
211begin
212 try
213 TimeParts := TListString.Create;
214 TimeParts.Explode(Value, ':', StrToStr);
215 if TryEncodeTime(StrToInt(TimeParts[0]), StrToInt(TimeParts[1]),
216 StrToInt(TimeParts[2]), 0, time) then
217 Result := Time else Result := 0;
218 finally
219 TimeParts.Free;
220 end;
221end;
222
223{ TSqlDatabase }
224
225procedure TSqlDatabase.Connect;
226var
227 NewSession: PMYSQL;
228 Rows: TDbRows;
229begin
230// mySQLClient1.Connect;
231 FSession := mysql_init(FSession);
232// FSession.charset := 'latin2';
233 NewSession := mysql_real_connect(FSession, PChar(HostName), PChar(UserName),
234 PChar(Password), PChar(Database), FPort, nil, CLIENT_LONG_PASSWORD + CLIENT_CONNECT_WITH_DB);
235 if Assigned(NewSession) then begin
236 FConnected := True;
237 FSession := NewSession;
238 end else FConnected := False;
239
240 if LastErrorNumber <> 0 then
241 raise EQueryError.Create(Format(SDatabaseQueryError, [LastErrorMessage]));
242
243 try
244 Rows := TDbRows.Create;
245 Query(Rows, 'SET NAMES ' + Encoding);
246 finally
247 Rows.Free;
248 end;
249end;
250
251procedure TSqlDatabase.Insert(ATable: string; Data: TDictionaryStringString;
252 Schema: string);
253var
254 DbNames: string;
255 DbValues: string;
256 I: Integer;
257 Value: string;
258 DbResult: TDbRows;
259begin
260 LastUsedTable := ATable;
261 DbNames := '';
262 DbValues := '';
263 for I := 0 to Data.Count - 1 do begin
264 Value := Data.Items[I].Value;
265 StringReplace(Value, '"', '\"', [rfReplaceAll]);
266 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
267 else DbValues := DbValues + ',"' + Value + '"';
268 DbNames := DbNames + ',`' + Data.Keys[I] + '`';
269 end;
270 System.Delete(DbNames, 1, 1);
271 System.Delete(DbValues, 1, 1);
272 try
273 DbResult := TDbRows.Create;
274 if Schema <> '' then Schema := '`' + Schema + '`.';
275 Query(DbResult, 'INSERT INTO ' + Schema + '`' + ATable + '` (' + DbNames + ') VALUES (' + DbValues + ')');
276 finally
277 DbResult.Free;
278 end;
279end;
280
281procedure TSqlDatabase.Query(DbRows: TDbRows; Data: string);
282var
283 I, II: Integer;
284 DbResult: PMYSQL_RES;
285 DbRow: MYSQL_ROW;
286begin
287 DbRows.Clear;
288 if Assigned(FOnLogQuery) then FOnLogQuery(Self, Data);
289 LastQuery := Data;
290 mysql_query(FSession, PChar(Data));
291 if LastErrorNumber <> 0 then begin
292 raise EQueryError.Create(Format(SDatabaseQueryError, [LastErrorMessage]));
293 end;
294
295 DbResult := mysql_store_result(FSession);
296 if Assigned(DbResult) then begin
297 DbRows.Count := mysql_num_rows(DbResult);
298 for I := 0 to DbRows.Count - 1 do begin
299 DbRow := mysql_fetch_row(DbResult);
300 DbRows[I] := TDictionaryStringString.Create;
301 with DbRows[I] do begin
302 for II := 0 to mysql_num_fields(DbResult) - 1 do begin
303 Add(mysql_fetch_field_direct(DbResult, II)^.Name,
304 PChar((DbRow + II)^));
305 end;
306 end;
307 end;
308 end;
309 mysql_free_result(DbResult);
310end;
311
312procedure TSqlDatabase.Replace(ATable: string; Data: TDictionaryStringString;
313 Schema: string = '');
314var
315 DbNames: string;
316 DbValues: string;
317 Value: string;
318 I: Integer;
319 DbResult: TDbRows;
320begin
321 LastUsedTable := ATable;
322 DbNames := '';
323 DbValues := '';
324 for I := 0 to Data.Count - 1 do begin
325 Value := Data.Items[I].Value;
326 StringReplace(Value, '"', '\"', [rfReplaceAll]);
327 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
328 else DbValues := DbValues + ',"' + Value + '"';
329 DbNames := DbNames + ',`' + Data.Keys[I] + '`';
330 end;
331 System.Delete(DbNames, 1, 1);
332 System.Delete(DbValues, 1, 1);
333 try
334 DbResult := TDbRows.Create;
335 if Schema <> '' then Schema := '`' + Schema + '`.';
336 Query(DbResult, 'REPLACE INTO ' + Schema + '`' + ATable + '` (' + DbNames + ') VALUES (' + DbValues + ')');
337 finally
338 DbResult.Free;
339 end;
340end;
341
342procedure TSqlDatabase.Select(DbRows: TDbRows; ATable: string; Filter: string = '*'; Condition: string = '1');
343begin
344 LastUsedTable := ATable;
345 Query(DbRows, 'SELECT ' + Filter + ' FROM `' + ATable + '` WHERE ' + Condition);
346end;
347
348procedure TSqlDatabase.Update(ATable: string; Data: TDictionaryStringString;
349 Condition: string = '1'; Schema: string = '');
350var
351 DbValues: string;
352 Value: string;
353 I: Integer;
354 DbResult: TDbRows;
355begin
356 LastUsedTable := ATable;
357 DbValues := '';
358 for I := 0 to Data.Count - 1 do begin
359 Value := Data.Items[I].Value;
360 StringReplace(Value, '"', '\"', [rfReplaceAll]);
361 if Value = 'NOW()' then DbValues := DbValues + ',' + Value
362 else DbValues := DbValues + ',`' + Data.Keys[I] + '` =' + '"' + Value + '"';
363 end;
364 System.Delete(DbValues, 1, 1);
365 try
366 DbResult := TDbRows.Create;
367 if Schema <> '' then Schema := '`' + Schema + '`.';
368 Query(DbResult, 'UPDATE ' + Schema + '`' + ATable + '` SET ' + DbValues + ' WHERE ' + Condition);
369 finally
370 DbResult.Free;
371 end;
372end;
373
374procedure TSqlDatabase.mySQLClient1ConnectError(Sender: TObject; Msg: String);
375begin
376// LastError := Msg + '('+IntToStr(mySQLClient1.LastErrorNumber)+')';
377end;
378
379procedure TSqlDatabase.Delete(ATable: string; Condition: string = '1';
380 Schema: string = '');
381var
382 DbResult: TDbRows;
383begin
384 LastUsedTable := ATable;
385 try
386 DbResult := TDbRows.Create;
387 if Schema <> '' then Schema := '`' + Schema + '`.';
388 Query(DbResult, 'DELETE FROM ' + Schema + '`' + ATable + '` WHERE ' + Condition);
389 finally
390 DbResult.Free;
391 end;
392end;
393
394function TSqlDatabase.GetConnected: Boolean;
395begin
396 Result := FConnected;
397end;
398
399procedure TSqlDatabase.Disconnect;
400begin
401 mysql_close(FSession);
402 FConnected := False;
403end;
404
405constructor TSqlDatabase.Create(AOwner: TComponent);
406begin
407 inherited;
408 FSession := nil;
409 Encoding := 'utf8';
410 FPort := 3306;
411end;
412
413function TSqlDatabase.LastInsertId: Integer;
414begin
415 Result := mysql_insert_id(FSession);
416end;
417
418function TSqlDatabase.GetLastErrorMessage: string;
419begin
420 Result := mysql_error(FSession);
421end;
422
423function TSqlDatabase.GetLastErrorNumber: Integer;
424begin
425 Result := mysql_errno(FSession);
426end;
427
428procedure TSqlDatabase.CreateDatabase;
429var
430 TempDatabase: string;
431 DbRows: TDbRows;
432begin
433 TempDatabase := Database;
434 Database := 'mysql';
435 Connect;
436 try
437 DbRows := TDbRows.Create;
438 Query(DbRows, 'CREATE DATABASE ' + TempDatabase);
439 finally
440 DbRows.Free;
441 end;
442 Disconnect;
443 Database := TempDatabase;
444end;
445
446procedure TSqlDatabase.CreateTable(Name: string);
447var
448 DbRows: TDbRows;
449begin
450 try
451 DbRows := TDbRows.Create;
452 Query(DbRows, 'CREATE TABLE `' + Name + '`' +
453 ' (`Id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`Id`));');
454 finally
455 DbRows.Free;
456 end;
457end;
458
459procedure TSqlDatabase.CreateColumn(Table, ColumnName: string;
460 ColumnType: TTypeKind);
461const
462 ColTypes: array[0..17] of string = ('', 'INT', 'CHAR', 'INT', 'DOUBLE',
463 'VARCHAR(255)', 'SET', 'INT', '', '', 'TEXT', 'TEXT', '', '', '', '', '', '');
464var
465 DbRows: TDbRows;
466begin
467 try
468 DbRows := TDbRows.Create;
469 Query(DbRows, 'ALTER TABLE `' + Table + '` ADD `' + ColumnName + '` ' +
470 ColTypes[Integer(ColumnType)] + ' NOT NULL');
471 finally
472 DbRows.Free;
473 end;
474end;
475
476destructor TSqlDatabase.Destroy;
477begin
478 if Connected then Disconnect;
479end;
480
481function TSqlDatabase.GetCharset: string;
482begin
483 Result := mysql_character_set_name(FSession);
484end;
485
486procedure TSqlDatabase.SetConnected(const AValue: Boolean);
487begin
488 if AValue = FConnected then Exit;
489 if AValue then Connect
490 else Disconnect;
491end;
492
493procedure TSqlDatabase.SetDatabase(const Value: string);
494begin
495 FDatabase := Value;
496 if FConnected then mysql_select_db(FSession, PChar(FDatabase));
497end;
498
499{ TDbRows }
500
501destructor TDbRows.Destroy;
502begin
503 inherited;
504end;
505
506function TDbRows.GetData(Index: Integer): TDictionaryStringString;
507begin
508 Result := TDictionaryStringString(Items[Index]);
509end;
510
511procedure TDbRows.SetData(Index: Integer; const Value: TDictionaryStringString);
512begin
513 Items[Index] := Value;
514end;
515
516end.
517
518
Note: See TracBrowser for help on using the repository browser.