-- upgrade 3.10

-- There shouldnt be any
DELETE FROM msg_ref WHERE FIND_IN_SET('vbr', auth) != 0 OR FIND_IN_SET('rep', auth) != 0 OR FIND_IN_SET('rep_s', auth) != 0;

ALTER TABLE msg_ref DROP COLUMN reputation, DROP COLUMN vbr,
MODIFY COLUMN auth SET ('author', 'spf_helo', 'spf', 'dkim', 'org', 'dmarc', 'aligned', 'dnswl', 'nx') NOT NULL;

/*
* Convert IP addresses from BINARY(4) to INET6.
* This works for IPv4 addresses only.
*/
ALTER TABLE message_in ADD COLUMN inet6_ip INET6 NOT NULL AFTER ip;
UPDATE message_in SET inet6_ip = CONCAT('::ffff:', INET_NTOA(CONV(HEX(ip),16,10)));
ALTER TABLE message_in DROP ip, RENAME COLUMN inet6_ip TO ip;
ALTER TABLE message_out ADD COLUMN inet6_ip INET6 NOT NULL AFTER ip;
UPDATE message_out SET inet6_ip = CONCAT('::ffff:', INET_NTOA(CONV(HEX(ip),16,10)));
ALTER TABLE message_out DROP ip, RENAME COLUMN inet6_ip TO ip;

/*
* Replace the procedure that had BINARY(4) for m_ip argument.
*/
delimiter //
DROP PROCEDURE IF EXISTS sent_message //
CREATE PROCEDURE sent_message (
  IN m_addr VARCHAR(63),
  IN m_ino INT UNSIGNED,
  IN m_mtime INT UNSIGNED,
  IN m_pid INT UNSIGNED,
  IN m_ip INET6,
  IN m_date VARCHAR(63),
  IN m_id VARCHAR(63),
  IN m_es VARCHAR(63),
  IN m_ct VARCHAR(63),
  IN m_ce VARCHAR(63),
  IN m_rcpt INT UNSIGNED)
  MODIFIES SQL DATA
BEGIN
  DECLARE user_ref INT UNSIGNED;
  DECLARE Empty_set CONDITION FOR 1329;
  DECLARE CONTINUE HANDLER FOR Empty_set
    BEGIN
      INSERT INTO user SET addr = m_addr;
      SELECT LAST_INSERT_ID() INTO user_ref;
    END;
  SELECT id INTO user_ref FROM user WHERE addr = m_addr LIMIT 1;
  INSERT INTO message_out SET ino = m_ino,
    mtime = m_mtime,
    pid = m_pid,
    ip = m_ip,
    user = user_ref,
    date = m_date,
    message_id = m_id,
    envelope_sender = m_es,
    content_type = m_ct,
    content_encoding = m_ce,
    rcpt_count = m_rcpt;
  SELECT user_ref, LAST_INSERT_ID() AS message_ref;
END //
