CREATE TEMPORARY TABLE `tmp_Part` (
  `oldPartId` int(11) NOT NULL DEFAULT '0',
  `preProduction` enum('y','n') NOT NULL DEFAULT 'y',
  `number` varchar(255) NOT NULL DEFAULT '',
  `name` varchar(255) NOT NULL DEFAULT '',
  `clientId` int(11) NOT NULL DEFAULT '0',
  `weight` float NOT NULL DEFAULT '0',
  `alloyTemper` varchar(255) NOT NULL DEFAULT '',
  `status` varchar(255) NOT NULL DEFAULT '',
  `thumb` varchar(255) DEFAULT NULL,
  `thumbSize` int(11) NOT NULL DEFAULT '0',
  `image` varchar(255) DEFAULT NULL,
  `imageSize` int(11) NOT NULL DEFAULT '0'
);

LOAD DATA LOCAL INFILE '/home/cfis/t150/02-details-part.csv'
#LOAD DATA LOCAL INFILE '/home/borey/public_html/carleyfoundry/trunk/import/t150/02-details-part.csv'

REPLACE INTO TABLE `tmp_Part`
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\;' LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

TRUNCATE TABLE cf_Part;
TRUNCATE TABLE cf_PartVersion;

ALTER TABLE `cf_Part` ADD `oldPartId` INT NOT NULL AFTER `sorter` ;

ALTER TABLE `cf_Part` ADD INDEX ( `oldPartId` ) ;

INSERT INTO cf_Part (`oldPartId`, `blockedVersion`, `added`, `changed`)
SELECT oldPartId, NULL, NOW(), NOW()
FROM tmp_Part
ORDER BY oldPartId;

INSERT INTO cf_PartVersion (`partId`, `preProduction`, `version`, `number`, `name`, `clientId`, `weight`, `alloyTemper`,
    `status`, `image`, `added`, `changed`)
SELECT p.id, `preProduction`, '1', tp.`number`, tp.`name`,  c.id, `weight`, `alloyTemper`, `status`,
    IF(`image` = '', `thumb`, `image`), NOW(), NOW()
FROM tmp_Part tp
    JOIN cf_Client c ON tp.clientId = c.number
    JOIN cf_Part p ON p.oldPartId = tp.oldPartId
ORDER BY p.id;

UPDATE cf_Part p
    JOIN cf_PartVersion pv on p.id = pv.partId
    SET sorter = p.id, currentVersion = pv.id;

DELETE FROM cf_zz_File WHERE `name` = `nameFs`;
INSERT INTO cf_zz_File (`name`, nameFs, `type`, `size`, added)
SELECT IF(`image` = '', `thumb`, `image`) AS `name`, IF(`image` = '', `thumb`, `image`),
    IF(SUBSTR(IF(`image` = '', `thumb`, `image`), -3) = 'jpg', 'image/jpeg', 'image/x-targa'),
    IF(`image` = '', `thumbSize`, `imageSize`), NOW()
FROM tmp_Part
WHERE IF(`image` = '', `thumb`, `image`)  != '';

