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.

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