Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   MySQL (https://www.clubdelphi.com/foros/forumdisplay.php?f=21)
-   -   Copiar la estructura de paradox a mysql (https://www.clubdelphi.com/foros/showthread.php?t=53302)

seoane 18-02-2008 11:45:47

Copiar la estructura de paradox a mysql
 
Estoy haciendo un programa para copiar los datos de unas tablas de paradox a MySql, el programa es muy sencillo pero necesita que la estructura de las tablas sea la misma en paradox y en mysql. En pricipio crear las tablas en MySql se pensaba hacer "a mano", pero he pensado que se podria automatizar el proceso de alguna manera.

Por ahora tengo el siguiente codigo que a partir de las tablas en paradox me genera un script para crear las tablas en MySql. Me gustaria que le echaseis un vistazo y me dierais vuestra opinion, decirme donde se puede mejorar, si estan bien escogidas las equivalencias entre los tipos de datos en paradox y en mysql, etc ...

Código Delphi [-]
var
  i,j: Integer;
  Str: String;
  Script, Conf, Aux: TStringList;
  Tabla: TTable;
begin
  with TSaveDialog.Create(nil) do
  try
    Filter:= '*.sql|*.sql';
    if Execute then
    begin
      Script:= TStringList.Create;
      try
        Conf:= TStringList.Create;
        // La lista con las tablas la guardo en un txt separado por comas
        Conf.LoadFromFile(ChangeFileExt(ParamStr(0),'.lst'));
        try
          Aux:= TStringList.Create;
          try
            Aux.Delimiter:= ';';
            Aux.QuoteChar:= '"';
            Script.Add('-- Script para crear las tablas');
            Script.Add('--');
            Script.Add('/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;');
            Script.Add('/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;');
            Script.Add('/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;');
            Script.Add('/*!40101 SET NAMES utf8 */;');
            Script.Add('');
            Script.Add('/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;');
            Script.Add('/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;');
            Script.Add('/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=''NO_AUTO_VALUE_ON_ZERO'' */;');
            Script.Add('');
            Tabla:= TTable.Create(nil);
            try
              for i:= 0 to Conf.Count - 1 do
              begin
                Aux.DelimitedText:= Conf.Strings[i];
                if Aux.Count <> 6 then
                  Continue;
                Str:= ExtractFileName(Aux[1]);
                Script.Add('DROP TABLE IF EXISTS `' + ChangeFileExt(Str,'') + '`;');
                Script.Add('CREATE TABLE `' + ChangeFileExt(Str,'') + '` (');
                Tabla.Active:= FALSE;
                Tabla.DatabaseName:= ExtractFilePath(Aux[1]);
                Tabla.TableName:= Str;
                Tabla.Open;
                for j:= 0 to Tabla.FieldCount - 1 do
                begin
                  Str:= '  `' + Tabla.Fields[j].FieldName + '` ';
                  case Tabla.Fields[j].DataType of
                    ftString: begin
                      Str:= Str + Format('VARCHAR(%d) NOT NULL default '''',',
                        [Tabla.Fields[j].DataSize]);
                    end;
                    ftSmallint: begin
                      Str:= Str + 'SMALLINT(6) NOT NULL default ''0'',';
                    end;
                    ftInteger: begin
                      Str:= Str + 'INT(11) NOT NULL default ''0'',';
                    end;
                    ftBoolean: begin
                      Str:= Str + 'TINYINT(1) NOT NULL default ''0'',';
                    end;
                    ftFloat: begin
                      Str:= Str + 'FLOAT(12) NOT NULL default ''0.00'',';
                    end;
                    ftCurrency: begin
                      Str:= Str + 'DECIMAL(10,2) NOT NULL default ''0.00'',';
                    end;
                    ftDate: begin
                      Str:= Str + 'DATE NOT NULL default ''1000-01-01'',';
                    end;
                    ftTime: begin
                      Str:= Str + 'TIME NOT NULL default ''00:00:00'',';
                    end;
                    ftDateTime: begin
                      Str:= Str + 'DATETIME NOT NULL default ''1000-01-01 00:00:00'',';
                    end;
                    ftGraphic: begin
                      Str:= Str + 'MEDIUMBLOB,';
                    end;
                    ftBlob: begin
                      Str:= Str + 'MEDIUMBLOB,';
                    end;
                    ftAutoInc: begin
                      Str:= Str + 'INT(11) NOT NULL default ''0'',';
                    end;
                    ftMemo: begin
                      Str:= Str + 'VARCHAR(255) NOT NULL default '''',';
                    end;
                  end;
                  Script.Add(Str);
                end;
                Str:= '  PRIMARY KEY (';
                for j:= 0 to Tabla.FieldCount - 1 do
                begin
                  if Tabla.Fields[j].IsIndexField then
                  begin
                    if j > 0 then
                      Str:= Str + ',';
                    Str:= Str + '`' + Tabla.Fields[j].FieldName +  '`';  
                  end;
                end;
                Script.Add(Str + ')');
                Script.Add(') ENGINE=MyISAM DEFAULT CHARSET=latin1;');
                Script.Add('');
              end;
            finally
              Tabla.Free;
            end;
            Script.Add('/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;');
            Script.Add('/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;');
            Script.Add('/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;');
            Script.Add('/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;');
            Script.Add('/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;');
            Script.Add('/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;');
            Script.Add('/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;');
            Script.SaveToFile(Filename);
          finally
            Aux.Free;
          end;
        finally
          Conf.Free;
        end;
      finally
        Script.Free;
      end;
    end;
  finally
    Free;
  end;
end;

Espero vuestras opiniones ...

Lepe 18-02-2008 12:49:44

Sobre la clave primaria:
Código Delphi [-]
Str:= '  PRIMARY KEY (';
                tabla.IndexDefs.Update;
                for j:= 0 to Tabla.IndexDefs.Count - 1 do
                begin
                  if [ixPrimary] in Tabla.IndexDefs[j].Options then
                  begin
                    if [ixDescending] in Tabla.IndexDefs[j].Options then
                      // pues eso, hazlo descendente
                    
                      Str:= ReplaceStr(Tabla.IndexDefs[j].Fields,  ';', ',');
                  end
                  else // puede ser un índice secundario, mantenido o no...
                end;

Saludos

seoane 18-02-2008 13:18:55

Gracias Lepe, aunque al probar tu ejemplo me encontre con un problema, no me reconoce la propiedad "Options" ¿puede ser porque uso delphi 7?

Lepe 18-02-2008 16:28:20

Con razón. Me equivoqué de propiedad, es en IndexDefs.

Edito el mensaje y lo corrigo.

De todas formas, revisa la clase TIndexDefs. Tiene más detalles de los que comento en ese mensaje

Asias

seoane 18-02-2008 18:14:38

Ahora va bien, solo hay que quitarle los corchetes a ixPrimary y ixDescending, por lo demas todo correcto.

Solo una pregunta mas: ¿que ventajas tiene tu forma de hacerlo con respecto a como lo hacia yo? es evidente que tu controlas que sea un indice primario o secundario, pero aparte de eso ¿tiene alguna otra ventaja que se me escapa y que deberia tener en cuenta? :confused:

Lepe 18-02-2008 22:03:33

No. Hecho así, se obtiene más datos sobre el índice, nada más. Si tu Base de datos no tiene índices secundarios, tu código va sobrado.

Indice de clave primaria
único o no
orden ascendente o descendente
... y si es mantenido o no es lo de menos (todos los índices deben ser mantenidos por Paradox o se corrompen creo recordar).

Saludos

seoane 18-02-2008 23:25:33

Muchas gracias Lepe :)


La franja horaria es GMT +2. Ahora son las 11:17:18.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi