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.

65 lines
2.0 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. GROUP BY city, state_id, country_id
  26. ON CONFLICT DO NOTHING""",
  27. )
  28. # Update city_id in res_better_zip
  29. openupgrade.logged_query(
  30. env.cr, """
  31. UPDATE res_better_zip rbz
  32. SET city_id = rc.id
  33. FROM res_city rc
  34. WHERE rc.name = rbz.city
  35. AND rc.state_id = rbz.state_id
  36. AND rc.country_id = rbz.country_id
  37. AND rbz.city_id IS NULL""",
  38. )
  39. # Create records for new model
  40. openupgrade.logged_query(
  41. env.cr, """
  42. INSERT INTO res_city_zip (
  43. %s, name, city_id
  44. )
  45. SELECT
  46. id, name, city_id
  47. FROM res_better_zip
  48. WHERE city_id IS NOT NULL
  49. ON CONFLICT DO NOTHING""",
  50. (AsIs(column_name), ),
  51. )
  52. # Recompute display name for entries inserted by SQL
  53. env['res.city.zip'].search([])._compute_new_display_name()
  54. # Link res.partner with corresponding new entries
  55. openupgrade.logged_query(
  56. env.cr, """
  57. UPDATE res_partner rp
  58. SET zip_id = rcz.id
  59. FROM res_city_zip rcz
  60. WHERE rcz.%s = rp.%s""",
  61. (AsIs(column_name), AsIs(openupgrade.get_legacy_name('zip_id')), ),
  62. )