You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB

  1. # Copyright 2018 Tecnativa - Pedro M. Baeza
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  3. from psycopg2.extensions import AsIs
  4. from openupgradelib import openupgrade
  5. @openupgrade.migrate()
  6. def migrate(env, version):
  7. column_name = openupgrade.get_legacy_name('better_zip_id')
  8. openupgrade.logged_query(
  9. env.cr,
  10. "ALTER TABLE res_city_zip ADD %s INTEGER", (AsIs(column_name), ),
  11. )
  12. # Create a city for ZIPs without it
  13. openupgrade.logged_query(
  14. env.cr, """
  15. INSERT INTO res_city (
  16. name, state_id, country_id,
  17. create_uid, create_date, write_uid, write_date
  18. )
  19. SELECT
  20. city, state_id, country_id,
  21. MIN(create_uid), MIN(create_date), MIN(write_uid), MIN(write_date)
  22. FROM res_better_zip rbz
  23. WHERE city_id IS NULL
  24. AND rbz.country_id IS NOT NULL
  25. AND rbz.name IS NOT NULL
  26. GROUP BY city, state_id, country_id
  27. ON CONFLICT DO NOTHING""",
  28. )
  29. # Update city_id in res_better_zip
  30. openupgrade.logged_query(
  31. env.cr, """
  32. UPDATE res_better_zip rbz
  33. SET city_id = rc.id
  34. FROM res_city rc
  35. WHERE rc.name = rbz.city
  36. AND rc.state_id = rbz.state_id
  37. AND rc.country_id = rbz.country_id
  38. AND rbz.city_id IS NULL""",
  39. )
  40. # Create records for new model
  41. openupgrade.logged_query(
  42. env.cr, """
  43. INSERT INTO res_city_zip (
  44. %s, name, city_id
  45. )
  46. SELECT
  47. id, name, city_id
  48. FROM res_better_zip
  49. WHERE city_id IS NOT NULL
  50. ON CONFLICT DO NOTHING""",
  51. (AsIs(column_name), ),
  52. )
  53. # Recompute display name for entries inserted by SQL
  54. env['res.city.zip'].search([])._compute_new_display_name()
  55. # Link res.partner with corresponding new entries
  56. openupgrade.logged_query(
  57. env.cr, """
  58. UPDATE res_partner rp
  59. SET zip_id = rcz.id
  60. FROM res_city_zip rcz
  61. WHERE rcz.%s = rp.%s""",
  62. (AsIs(column_name), AsIs(openupgrade.get_legacy_name('zip_id')), ),
  63. )