function BytesToHex(const Bytes: TBytes): string;
var
i: Integer;
begin
Result:= '';
for i:= 0 to Length(Bytes) - 1 do Result:= Result + IntToHex(Bytes[i], 2);
end;
try
Writeln(ReportFile, 'Update Scripts for endereco Records with Older data_cadastro');
Writeln(ReportFile, 'Generated on: ' + DateTimeToStr(now));
Writeln(ReportFile, '--------------------------------------------------------');
Writeln(ReportFile, '');
QueryStore1.SQL.Text:= 'SELECT endereco_id, cliente_id, data_cadastro ' + 'FROM centauro001.endereco ORDER BY endereco_id';
QueryStore2.SQL.Text:= 'SELECT endereco_id, cliente_id, data_cadastro ' + 'FROM centauro005.endereco ORDER BY endereco_id';
QueryStore1.Open;
QueryStore2.Open;
while not QueryStore2.Eof do
begin
enderecoId:= QueryStore2.FieldByName('endereco_id').AsInteger;
clienteId:= QueryStore2.FieldByName('cliente_id').AsInteger;
dataCadastro2:= QueryStore2.FieldByName('data_cadastro').AsDateTime;
code
CompositeKey:= Format('%d:%d', [enderecoId, clienteId]);
if not Store2Keys.ContainsKey(CompositeKey) then Store2Keys.Add(CompositeKey, dataCadastro2)
else Writeln(ReportFile, Format('Duplicate key found in centauro005 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
QueryStore2.Next;
end;
QueryStore1.First;
while not QueryStore1.Eof do
begin
enderecoId:= QueryStore1.FieldByName('endereco_id').AsInteger;
clienteId:= QueryStore1.FieldByName('cliente_id').AsInteger;
dataCadastro1:= QueryStore1.FieldByName('data_cadastro').AsDateTime;
code
CompositeKey:= Format('%d:%d', [enderecoId, clienteId]);
if Store2Keys.ContainsKey(CompositeKey) then
begin
dataCadastro2:= Store2Keys[CompositeKey];
if dataCadastro1 <> dataCadastro2 then
begin
isStore1Newer:= dataCadastro1 > dataCadastro2;
if isStore1Newer then
begin
SourceQuery:= TUniQuery.Create(nil);
try
SourceQuery.Connection:= Connection;
SourceQuery.SQL.Text:= 'SELECT * FROM centauro001.endereco WHERE endereco_id = :id AND cliente_id = :cid';
SourceQuery.ParamByName('id').AsInteger:= enderecoId;
SourceQuery.ParamByName('cid').AsInteger:= clienteId;
SourceQuery.Open;
if SourceQuery.IsEmpty then
begin
Writeln(ReportFile, Format('Warning: Record not found in centauro001 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
end
else
begin
TargetQuery:= TUniQuery.Create(nil);
try
TargetQuery.Connection:= Connection;
TargetQuery.SQL.Text:= 'SELECT * FROM centauro005.endereco WHERE endereco_id = :id AND cliente_id = :cid';
TargetQuery.ParamByName('id').AsInteger:= enderecoId;
TargetQuery.ParamByName('cid').AsInteger:= clienteId;
TargetQuery.Open;
if TargetQuery.IsEmpty then
begin
Writeln(ReportFile, Format('Warning: Corresponding record not found in centauro005 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
end
else
begin
FieldList:= TStringList.Create;
try
for i:= 0 to SourceQuery.FieldCount - 1 do
begin
FieldName:= SourceQuery.Fields[i].FieldName;
if (FieldName <> 'endereco_id') and (FieldName <> 'cliente_id') then FieldList.Add(FieldName);
end;
// Initialize SET clause
SetClause:= '';
for i:= 0 to FieldList.Count - 1 do
begin
FieldName:= FieldList[i];
ValueStore1:= SourceQuery.FieldByName(FieldName).Value;
FieldType:= SourceQuery.FieldByName(FieldName).DataType;
if i > 0 then SetClause:= SetClause + ', ';
SetClause:= SetClause + Format('%s = %s', [FieldName, FormatSQLValue(ValueStore1, FieldType)]);
end;
// Construct the full UPDATE statement
sqlUpdate:= Format('UPDATE centauro005.endereco SET %s WHERE endereco_id = %d AND cliente_id = %d;', [SetClause, enderecoId, clienteId]);
Writeln(ScriptFile, sqlUpdate);
Writeln(ReportFile, Format('endereco_id=%d, cliente_id=%d: Updated centauro005.endereco (data_cadastro=%s) ' + 'with data from centauro001.endereco (data_cadastro=%s)',
[enderecoId, clienteId, DateTimeToStr(dataCadastro2), DateTimeToStr(dataCadastro1)]));
Writeln(ReportFile, sqlUpdate);
Writeln(ReportFile, '--------------------------------------------------------');
finally
FieldList.Free;
end;
end;
finally
TargetQuery.Free;
end;
end;
finally
SourceQuery.Free;
end;
end
else
begin
SourceQuery:= TUniQuery.Create(nil);
try
SourceQuery.Connection:= Connection;
SourceQuery.SQL.Text:= 'SELECT * FROM centauro005.endereco WHERE endereco_id = :id AND cliente_id = :cid';
SourceQuery.ParamByName('id').AsInteger:= enderecoId;
SourceQuery.ParamByName('cid').AsInteger:= clienteId;
SourceQuery.Open;
if SourceQuery.IsEmpty then
begin
Writeln(ReportFile, Format('Warning: Record not found in centauro005 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
end
else
begin
TargetQuery:= TUniQuery.Create(nil);
try
TargetQuery.Connection:= Connection;
TargetQuery.SQL.Text:= 'SELECT * FROM centauro001.endereco WHERE endereco_id = :id AND cliente_id = :cid';
TargetQuery.ParamByName('id').AsInteger:= enderecoId;
TargetQuery.ParamByName('cid').AsInteger:= clienteId;
TargetQuery.Open;
if TargetQuery.IsEmpty then
begin
Writeln(ReportFile, Format('Warning: Corresponding record not found in centauro001 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
end
else
begin
FieldList:= TStringList.Create;
try
for i:= 0 to SourceQuery.FieldCount - 1 do
begin
FieldName:= SourceQuery.Fields[i].FieldName;
if (FieldName <> 'endereco_id') and (FieldName <> 'cliente_id') then FieldList.Add(FieldName);
end;
// Initialize SET clause
SetClause:= '';
for i:= 0 to FieldList.Count - 1 do
begin
FieldName:= FieldList[i];
ValueStore2:= SourceQuery.FieldByName(FieldName).Value;
FieldType:= SourceQuery.FieldByName(FieldName).DataType;
if i > 0 then SetClause:= SetClause + ', ';
SetClause:= SetClause + Format('%s = %s', [FieldName, FormatSQLValue(ValueStore2, FieldType)]);
end;
// Construct the full UPDATE statement
sqlUpdate:= Format('UPDATE centauro001.endereco SET %s WHERE endereco_id = %d AND cliente_id = %d;', [SetClause, enderecoId, clienteId]);
Writeln(ScriptFile, sqlUpdate);
Writeln(ReportFile, Format('endereco_id=%d, cliente_id=%d: Updated centauro001.endereco (data_cadastro=%s) ' + 'with data from centauro005.endereco (data_cadastro=%s)',
[enderecoId, clienteId, DateTimeToStr(dataCadastro1), DateTimeToStr(dataCadastro2)]));
Writeln(ReportFile, sqlUpdate);
Writeln(ReportFile, '--------------------------------------------------------');
finally
FieldList.Free;
end;
end;
finally
TargetQuery.Free;
end;
end;
finally
SourceQuery.Free;
end;
end;
end;
end;
QueryStore1.Next;
ShowMessage('Update scripts and report have been generated successfully.' + sLineBreak + 'Script File: ' + ScriptFileName + sLineBreak + 'Report File: ' + ReportFileName);
end;
end.
Change the way that the updates on this method are done. Use something like:
REPLACE INTO centauro005.endereco SELECT * FROM centauro001.endereco_id
To modify your GenerateUpdateScriptsForOldDataCadastro procedure to use REPLACE INTO instead of UPDATE statements, you'll need to adjust how the SQL scripts are generated. The REPLACE INTO statement effectively performs a delete followed by an insert, ensuring that the target table has the latest data from the source table. This approach can simplify synchronization between your centauro001 and centauro005 schemas.
Below are detailed steps and code adjustments to achieve this:
1. Understanding REPLACE INTO
REPLACE INTO works similarly to INSERT INTO, but with the following differences:
Behavior: If a row with the same primary key or unique key exists, REPLACE INTO deletes the existing row and inserts the new row. If no such row exists, it simply inserts the new row.
Use Case: Ideal for scenarios where you want to ensure that the target table has the latest version of a row, replacing any existing duplicates based on unique constraints.
Important Considerations:
Unique Constraints: Ensure that your tables have appropriate unique constraints that define what constitutes a duplicate. In your case, since you're using a composite key (endereco_id, cliente_id) logically, consider adding a unique index on these columns if not already present.
sql
ALTER TABLE `endereco`
ADD UNIQUE KEY `unique_endereco_cliente` (`endereco_id`, `cliente_id`);
Auto-Increment Fields: Be cautious with AUTO_INCREMENT fields. When using REPLACE INTO, the auto-increment value may increment even if a row is replaced.
2. Modifying the Procedure
Here’s how you can adjust your Delphi-like procedure to generate REPLACE INTO statements:
a. Update Key Sections
Replace the sections where UPDATE statements are generated with REPLACE INTO statements.
b. Generate REPLACE INTO Statements
Instead of creating a SET clause for updates, you'll construct a REPLACE INTO statement that includes all field values.
c. Code Adjustments
Below is the adjusted procedure with comments highlighting the changes:
pascal
d. Explanation of Changes
Script and Report Filenames: Changed to replace_data_cadastro.sql and replace_data_cadastro_report.txt to reflect the new operation.
Generating REPLACE INTO Statements:
Fields and Values: Instead of creating a SET clause for each field, we generate two separate clauses: one for the field names and another for their corresponding values.
sqlReplace := Format('REPLACE INTO centauro005.endereco (%s) VALUES (%s);', [FieldsClause, ValuesClause]);
Writing to Script and Report: The REPLACE INTO statement is written to both the script file and the report for transparency.
Handling Both Directions: The procedure handles both updating centauro005 with data from centauro001 and vice versa by generating appropriate REPLACE INTO statements in both schemas.
Unique Key Consideration: Ensure that the unique key (endereco_id, cliente_id) is properly defined in both schemas to allow REPLACE INTO to function correctly.
3. Additional Recommendations
a. Bulk Operations
If the datasets are large, generating individual REPLACE INTO statements might be inefficient. Consider using bulk operations or batch processing where possible. For example:
sql
REPLACE INTO centauro005.endereco
SELECT * FROM centauro001.endereco
WHERE (endereco_id, cliente_id) IN (SELECT endereco_id, cliente_id FROM centauro001.endereco WHERE data_cadastro > (SELECT data_cadastro FROM centauro005.endereco WHERE centauro005.endereco.endereco_id = centauro001.endereco.endereco_id));
Note: The above SQL is a generalized example and may require adjustments based on your specific constraints and database engine capabilities.
b. Transaction Management
Wrap your REPLACE INTO operations within transactions to ensure data integrity. This way, if an error occurs, you can roll back all changes.
sql
START TRANSACTION;
-- Your REPLACE INTO statements here
COMMIT;
c. Index Optimization
Ensure that the columns used in the WHERE clauses and unique constraints are properly indexed to optimize performance.
d. Backup Before Replacement
Always back up your data before performing bulk REPLACE INTO operations, as this statement will delete existing rows that match the unique keys before inserting new ones.
4. Final Thoughts
Transitioning from UPDATE to REPLACE INTO can simplify the process of ensuring that your target schema reflects the latest data from the source schema. However, it's crucial to understand the implications, especially regarding unique constraints and auto-increment fields. Always test the changes in a development or staging environment before applying them to production to avoid unintended data loss.
Feel free to reach out if you need further assistance or clarification on specific parts of the procedure!
Not yet included in a published release.
procedure GenerateReplaceScriptsForDataCadastro;
function BytesToHex(const Bytes: TBytes): string;
var
i: Integer;
begin
Result := '';
for i := 0 to Length(Bytes) - 1 do
Result := Result + IntToHex(Bytes[i], 2);
end;
function FormatSQLValue(const Value: Variant; const FieldType: TFieldType): string;
begin
if VarIsNull(Value) then
Result := 'NULL'
else
case FieldType of
ftString, ftWideString, ftMemo, ftWideMemo, ftFixedChar, ftFixedWideChar:
Result := QuotedStr(VarToStr(Value));
ftDate, ftDateTime, ftTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', Value));
ftInteger, ftSmallint, ftWord, ftLargeint, ftAutoInc, ftFloat, ftCurrency, ftBCD, ftFMTBcd:
Result := VarToStr(Value);
ftBytes, ftVarBytes, ftBlob, ftGraphic, ftOraBlob, ftOraClob, ftParadoxOle, ftDBaseOle:
Result := '0x' + BytesToHex(Value);
else
Result := QuotedStr(VarToStr(Value));
end;
end;
var
QueryStore1, QueryStore2: TUniQuery;
ScriptFile, ReportFile: TextFile;
ScriptFileName, ReportFileName: string;
enderecoId, clienteId: Integer;
dataCadastro1, dataCadastro2: TDateTime;
isStore1Newer: Boolean;
FieldList: TStringList;
i: Integer;
FieldName: string;
ValueStore1, ValueStore2: Variant;
FieldType: TFieldType;
Connection: TUniConnection;
Store2Keys: TDictionary<string, TDateTime>;
CompositeKey: string;
SourceQuery, TargetQuery: TUniQuery;
sqlReplace: string;
FieldsClause, ValuesClause: string;
begin
ScriptFileName := 'replace_data_cadastro.sql';
ReportFileName := 'replace_data_cadastro_report.txt';
AssignFile(ScriptFile, ScriptFileName);
Rewrite(ScriptFile);
AssignFile(ReportFile, ReportFileName);
Rewrite(ReportFile);
QueryStore1 := TUniQuery.Create(nil);
QueryStore2 := TUniQuery.Create(nil);
Store2Keys := TDictionary<string, TDateTime>.Create;
try
Writeln(ReportFile, 'Replace Scripts for endereco Records with Older data_cadastro');
Writeln(ReportFile, 'Generated on: ' + DateTimeToStr(now));
Writeln(ReportFile, '--------------------------------------------------------');
Writeln(ReportFile, '');
Connection := DM.LocalServer;
QueryStore1.Connection := Connection;
QueryStore2.Connection := Connection;
QueryStore1.SQL.Text := 'SELECT * FROM centauro001.endereco ORDER BY endereco_id';
QueryStore2.SQL.Text := 'SELECT * FROM centauro005.endereco ORDER BY endereco_id';
QueryStore1.Open;
QueryStore2.Open;
// Build a dictionary for centauro005 for quick lookup
while not QueryStore2.Eof do
begin
enderecoId := QueryStore2.FieldByName('endereco_id').AsInteger;
clienteId := QueryStore2.FieldByName('cliente_id').AsInteger;
dataCadastro2 := QueryStore2.FieldByName('data_cadastro').AsDateTime;
CompositeKey := Format('%d:%d', [enderecoId, clienteId]);
if not Store2Keys.ContainsKey(CompositeKey) then
Store2Keys.Add(CompositeKey, dataCadastro2)
else
Writeln(ReportFile, Format('Duplicate key found in centauro005 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
QueryStore2.Next;
end;
QueryStore1.First;
while not QueryStore1.Eof do
begin
enderecoId := QueryStore1.FieldByName('endereco_id').AsInteger;
clienteId := QueryStore1.FieldByName('cliente_id').AsInteger;
dataCadastro1 := QueryStore1.FieldByName('data_cadastro').AsDateTime;
CompositeKey := Format('%d:%d', [enderecoId, clienteId]);
if Store2Keys.ContainsKey(CompositeKey) then
begin
dataCadastro2 := Store2Keys[CompositeKey];
if dataCadastro1 <> dataCadastro2 then
begin
isStore1Newer := dataCadastro1 > dataCadastro2;
if isStore1Newer then
begin
// Prepare to replace into centauro005.endereco with data from centauro001.endereco
SourceQuery := TUniQuery.Create(nil);
try
SourceQuery.Connection := Connection;
SourceQuery.SQL.Text := 'SELECT * FROM centauro001.endereco WHERE endereco_id = :id AND cliente_id = :cid';
SourceQuery.ParamByName('id').AsInteger := enderecoId;
SourceQuery.ParamByName('cid').AsInteger := clienteId;
SourceQuery.Open;
if SourceQuery.IsEmpty then
begin
Writeln(ReportFile, Format('Warning: Record not found in centauro001 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
end
else
begin
// Build field and value clauses
FieldList := TStringList.Create;
try
FieldsClause := '';
ValuesClause := '';
for i := 0 to SourceQuery.FieldCount - 1 do
begin
FieldName := SourceQuery.Fields[i].FieldName;
if i > 0 then
begin
FieldsClause := FieldsClause + ', ';
ValuesClause := ValuesClause + ', ';
end;
FieldsClause := FieldsClause + '`' + FieldName + '`';
ValueStore1 := SourceQuery.Fields[i].Value;
FieldType := SourceQuery.Fields[i].DataType;
ValuesClause := ValuesClause + FormatSQLValue(ValueStore1, FieldType);
end;
// Construct the REPLACE INTO statement
sqlReplace := Format('REPLACE INTO centauro005.endereco (%s) VALUES (%s);', [FieldsClause, ValuesClause]);
Writeln(ScriptFile, sqlReplace);
Writeln(ReportFile, Format('endereco_id=%d, cliente_id=%d: Replaced centauro005.endereco (data_cadastro=%s) ' +
'with data from centauro001.endereco (data_cadastro=%s)',
[enderecoId, clienteId, DateTimeToStr(dataCadastro2), DateTimeToStr(dataCadastro1)]));
Writeln(ReportFile, sqlReplace);
Writeln(ReportFile, '--------------------------------------------------------');
finally
FieldList.Free;
end;
end;
finally
SourceQuery.Free;
end;
end
else
begin
// Prepare to replace into centauro001.endereco with data from centauro005.endereco
SourceQuery := TUniQuery.Create(nil);
try
SourceQuery.Connection := Connection;
SourceQuery.SQL.Text := 'SELECT * FROM centauro005.endereco WHERE endereco_id = :id AND cliente_id = :cid';
SourceQuery.ParamByName('id').AsInteger := enderecoId;
SourceQuery.ParamByName('cid').AsInteger := clienteId;
SourceQuery.Open;
if SourceQuery.IsEmpty then
begin
Writeln(ReportFile, Format('Warning: Record not found in centauro005 for endereco_id=%d and cliente_id=%d.', [enderecoId, clienteId]));
end
else
begin
// Build field and value clauses
FieldList := TStringList.Create;
try
FieldsClause := '';
ValuesClause := '';
for i := 0 to SourceQuery.FieldCount - 1 do
begin
FieldName := SourceQuery.Fields[i].FieldName;
if i > 0 then
begin
FieldsClause := FieldsClause + ', ';
ValuesClause := ValuesClause + ', ';
end;
FieldsClause := FieldsClause + '`' + FieldName + '`';
ValueStore2 := SourceQuery.Fields[i].Value;
FieldType := SourceQuery.Fields[i].DataType;
ValuesClause := ValuesClause + FormatSQLValue(ValueStore2, FieldType);
end;
// Construct the REPLACE INTO statement
sqlReplace := Format('REPLACE INTO centauro001.endereco (%s) VALUES (%s);', [FieldsClause, ValuesClause]);
Writeln(ScriptFile, sqlReplace);
Writeln(ReportFile, Format('endereco_id=%d, cliente_id=%d: Replaced centauro001.endereco (data_cadastro=%s) ' +
'with data from centauro005.endereco (data_cadastro=%s)',
[enderecoId, clienteId, DateTimeToStr(dataCadastro1), DateTimeToStr(dataCadastro2)]));
Writeln(ReportFile, sqlReplace);
Writeln(ReportFile, '--------------------------------------------------------');
finally
FieldList.Free;
end;
end;
finally
SourceQuery.Free;
end;
end;
end;
end;
QueryStore1.Next;
end;
finally
Store2Keys.Free;
QueryStore1.Free;
QueryStore2.Free;
CloseFile(ScriptFile);
CloseFile(ReportFile);
end;
ShowMessage('Replace scripts and report have been generated successfully.' + sLineBreak +
'Script File: ' + ScriptFileName + sLineBreak + 'Report File: ' + ReportFileName);
end;