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.

nestedset.py 11 KiB

11 years ago
Postgres support for Frappe (#5919) * [start] postgres * [wip] started refactoring db_schema * Add psycopg2 to requirements.txt * Add support for Postgres SQL - Separate frameworkSQL, database, schema, setup_db file for mariaDB and postgres - WIP * Remove quotes from sql to make it compatible with postgres as well * Moved some code from db_schema to database.py * Move code from db_schema to schema.py Add other required refactoring * Add schema chages * Remove redundant code in file * Add invalid column name exception class to exceptions.py * Add back tick in query wherever needed and replace ifnull with coalesce * Update get_column_description code in database.py file * Remove a print statement * Add keys to get on_duplicate query * Add bactick wherever necessary - Remove db_schema.py file * Remove DATE_SUB as it is incompatible with postgres - Fix prepare_filter_condition * Add backtick and quotes wherever necessary - Move get_database_size to frappe.db namespace - fix some left out bugs and errors * Add code to create key and unique index - added mysql and posgres in their respective database.py * Add more bacticks in queries and fix some errors - Pass keys to on_duplicate_update method - Replace MONTH with EXTRACT function - Remove DATEDIFF and CURDATE usage * Cast state value to int in toggle_two_factor_auth - since two_factor_auth has the datatype of Int * Refactor - Replace Timediff with normal arithmetic operator - Add MAX_COLUMN_LENGTH - Remove Redundant code - Add regexp character constant - Move create_help_table to database.py - Add get_full_text_search_condition method - Inherit MariaDBTable from DBTable * Replace Database instance with get_db method * Move db_manager to separate file * Refactor - Remove some unwanted code - Separate alter table code for postgres and mysql - Replace data_type with column_type in database.py * Make fulltext search changes in global_search.py * Add empty string check * Add root_password to site config * Create cli command for postgres console * Move setup of help database to setup_db.py * Add get_database_list method * Fix exception handling - Replace bad_field handler with missing_column handler * Fix tests and sql queries * Fix import error * Fix typo db -> database * Fix error with make_table in help.py * Try test for postgres * Remove pyhton 2.7 version to try postgres travis test * Add test fixes * Add db_type to the config of test_site_postgres * Enable query debug to check the reason for travis fail * Add backticks to check if the test passes * Update travis.yml - Add postgres addon * Try appending 'd_' to hash for db_name - since postgres does not support dbname starting with a number * Try adding db_type for global help to make travis work * Add print statements to debug travis failure * Enable transaction and remove debug flag * Fix help table creation query (postgres) * Fix import issue * Add some checks to prevent errors - Some doctypes used to get called even before they are created * Try fixes * Update travis config * Fix create index for help table * Remove unused code * Fix queries and update travis config * Fix ifnull replace logic (regex) * Add query fixes and code cleanup * Fix typo - get_column_description -> get_table_columns_description * Fix tests - Replace double quotes in query with single quote * Replace psycopg2 with psycopg2-binary to avoid warnings - http://initd.org/psycopg/docs/install.html#binary-install-from-pypi * Add multisql api * Add few multisql queries * Remove print statements * Remove get_fulltext_search_condition method and replace with multi query * Remove text slicing in create user * Set default for 'values' argument in multisql * Fix incorrect queries and remove few debug flags - Fix multisql bug * Force delete user to fix test - Fix Import error - Fix incorrect query * Fix query builder bug * Fix bad query * Fix query (minor) * Convert boolean text to int since is_private has datatype of int - Some query changes like removed double quotes and replace with interpolated string to pass multiple value pass in one of the query * Extend database class from an object to support python 2 * Fix query - Add quotes around value passed to the query for variable comparision * Try setting host_name for each test site - To avoid "RemoteDisconnected" error while testing data migration test - Update travis.yml to add hosts - Remove unwanted commit in setup_help_database * Set site hostname to data migration connector (in test file) - To connect the same site host * Fix duplicate entry issue - the problem is in naming series file. In previous commits I unknowingly changed a part of a series query due to which series were not getting reset * Replace few sql queries with orm methods * Fix codacy * Fix 'Doctype Sessions not found' issue * Fix bugs induced during codacy fixes * Fix Notification Test - Use ORM instead of raw sql * Set Date fallback value to 0001-01-01 - 0000-00-00 is invalid date in Postgres - 0001-01-01 works in both * Fix date filter method * Replace double quotes with single quote for literal value * Remove print statement * Replace double quotes with single * Fix tests - Replace few raw sql with ORM * Separate query for postgres - update_fields_to_fetch_query * Fix tests - replace locate with strpos for postgres * Fix tests - Skip test for datediff - convert bytes to str in escape method * Remove TestBot * Skip fieldname extraction * Replace docshare raw sql with ORM * Fix typo * Fix ancestor query test * Fix test data migration * Remove hardcoded hostname * Add default option and option list for db_type * Remove frappe.async module * Remove a debug flag from test * Fix codacy * fix import issue * Convert classmethod to static method * Convert few instance methods to static methods * Remove some unused imports * Fix codacy - Add exception type - Replace few instance methods with static methods - Remove unsued import * Fix codacy * Remove unused code * Remove some unused codes - Convert some instance methods to static function * Fix a issue with query modification * Fix add_index query * Fix query * Fix update_auth patch * Fix a issue with exception handling * Add try catch to a reload_doc * Add try-catch to file_manager_hook patch * import update_gravatar to set_user_gravatar patch * Undo all the wrong patch fixes * Fix db_setup code 😪 - previously it was not restoring db from source SQL which is why few old patched were breaking (because they were getting different schema structure) * Fix typo ! * Fix exception(is_missing_column) handling * Add deleted code - This code is only used in a erpnext patch. Can be moved to that patch file * Fix codacy * Replace a mariadb specific function in a query used in validate_series * Remove a debug flag * Revert changes (rename_parent_and_child) * Fix validate_one_root method * Fix date format issue * Fix codacy - Disable a pylint for variable argument warning - Convert an instance method to static method * Add bandit.yml The Codacy seems to use Bandit which generates warning for every subprocess import and its usage during pytest Since we have carefully used subprocess (avoided user input), warnings needs to be avoided. This can be removed if we have any alternative for subprocess usage. * Skip start_process_with_partial_path check * Fix typo * Add python 2.7 test * Move python versions in travis.yml * Add python versions to jobs * Overwrite python version inheritance for postgres in travis.yml * Add quotes around python version in .travis.yml * Add quotes around the name of the job * Try a travis fix * Try .travis.yml fix * Import missing subprocess * Refactor travis.yml * Refactor travis.yml - move install and tests commands to separate files - Use matrix to build combination of python version and db type * Make install.sh and run-tests.sh executable * Add sudo required to travis.yml to allow sudo cmmands in shell files * Load nvm * Remove verbose flag from scripts * Remove command-trace-print flag * Change to build dir in before script * Add absolute path for scripts * Fix tests * Fix typo * Fix codacy - fixes - "echo won't expand escape sequences." warning * Append (_) underscore instead of 'd' for db_name * Remove printf and use mysql execute flag
6 years ago
Postgres support for Frappe (#5919) * [start] postgres * [wip] started refactoring db_schema * Add psycopg2 to requirements.txt * Add support for Postgres SQL - Separate frameworkSQL, database, schema, setup_db file for mariaDB and postgres - WIP * Remove quotes from sql to make it compatible with postgres as well * Moved some code from db_schema to database.py * Move code from db_schema to schema.py Add other required refactoring * Add schema chages * Remove redundant code in file * Add invalid column name exception class to exceptions.py * Add back tick in query wherever needed and replace ifnull with coalesce * Update get_column_description code in database.py file * Remove a print statement * Add keys to get on_duplicate query * Add bactick wherever necessary - Remove db_schema.py file * Remove DATE_SUB as it is incompatible with postgres - Fix prepare_filter_condition * Add backtick and quotes wherever necessary - Move get_database_size to frappe.db namespace - fix some left out bugs and errors * Add code to create key and unique index - added mysql and posgres in their respective database.py * Add more bacticks in queries and fix some errors - Pass keys to on_duplicate_update method - Replace MONTH with EXTRACT function - Remove DATEDIFF and CURDATE usage * Cast state value to int in toggle_two_factor_auth - since two_factor_auth has the datatype of Int * Refactor - Replace Timediff with normal arithmetic operator - Add MAX_COLUMN_LENGTH - Remove Redundant code - Add regexp character constant - Move create_help_table to database.py - Add get_full_text_search_condition method - Inherit MariaDBTable from DBTable * Replace Database instance with get_db method * Move db_manager to separate file * Refactor - Remove some unwanted code - Separate alter table code for postgres and mysql - Replace data_type with column_type in database.py * Make fulltext search changes in global_search.py * Add empty string check * Add root_password to site config * Create cli command for postgres console * Move setup of help database to setup_db.py * Add get_database_list method * Fix exception handling - Replace bad_field handler with missing_column handler * Fix tests and sql queries * Fix import error * Fix typo db -> database * Fix error with make_table in help.py * Try test for postgres * Remove pyhton 2.7 version to try postgres travis test * Add test fixes * Add db_type to the config of test_site_postgres * Enable query debug to check the reason for travis fail * Add backticks to check if the test passes * Update travis.yml - Add postgres addon * Try appending 'd_' to hash for db_name - since postgres does not support dbname starting with a number * Try adding db_type for global help to make travis work * Add print statements to debug travis failure * Enable transaction and remove debug flag * Fix help table creation query (postgres) * Fix import issue * Add some checks to prevent errors - Some doctypes used to get called even before they are created * Try fixes * Update travis config * Fix create index for help table * Remove unused code * Fix queries and update travis config * Fix ifnull replace logic (regex) * Add query fixes and code cleanup * Fix typo - get_column_description -> get_table_columns_description * Fix tests - Replace double quotes in query with single quote * Replace psycopg2 with psycopg2-binary to avoid warnings - http://initd.org/psycopg/docs/install.html#binary-install-from-pypi * Add multisql api * Add few multisql queries * Remove print statements * Remove get_fulltext_search_condition method and replace with multi query * Remove text slicing in create user * Set default for 'values' argument in multisql * Fix incorrect queries and remove few debug flags - Fix multisql bug * Force delete user to fix test - Fix Import error - Fix incorrect query * Fix query builder bug * Fix bad query * Fix query (minor) * Convert boolean text to int since is_private has datatype of int - Some query changes like removed double quotes and replace with interpolated string to pass multiple value pass in one of the query * Extend database class from an object to support python 2 * Fix query - Add quotes around value passed to the query for variable comparision * Try setting host_name for each test site - To avoid "RemoteDisconnected" error while testing data migration test - Update travis.yml to add hosts - Remove unwanted commit in setup_help_database * Set site hostname to data migration connector (in test file) - To connect the same site host * Fix duplicate entry issue - the problem is in naming series file. In previous commits I unknowingly changed a part of a series query due to which series were not getting reset * Replace few sql queries with orm methods * Fix codacy * Fix 'Doctype Sessions not found' issue * Fix bugs induced during codacy fixes * Fix Notification Test - Use ORM instead of raw sql * Set Date fallback value to 0001-01-01 - 0000-00-00 is invalid date in Postgres - 0001-01-01 works in both * Fix date filter method * Replace double quotes with single quote for literal value * Remove print statement * Replace double quotes with single * Fix tests - Replace few raw sql with ORM * Separate query for postgres - update_fields_to_fetch_query * Fix tests - replace locate with strpos for postgres * Fix tests - Skip test for datediff - convert bytes to str in escape method * Remove TestBot * Skip fieldname extraction * Replace docshare raw sql with ORM * Fix typo * Fix ancestor query test * Fix test data migration * Remove hardcoded hostname * Add default option and option list for db_type * Remove frappe.async module * Remove a debug flag from test * Fix codacy * fix import issue * Convert classmethod to static method * Convert few instance methods to static methods * Remove some unused imports * Fix codacy - Add exception type - Replace few instance methods with static methods - Remove unsued import * Fix codacy * Remove unused code * Remove some unused codes - Convert some instance methods to static function * Fix a issue with query modification * Fix add_index query * Fix query * Fix update_auth patch * Fix a issue with exception handling * Add try catch to a reload_doc * Add try-catch to file_manager_hook patch * import update_gravatar to set_user_gravatar patch * Undo all the wrong patch fixes * Fix db_setup code 😪 - previously it was not restoring db from source SQL which is why few old patched were breaking (because they were getting different schema structure) * Fix typo ! * Fix exception(is_missing_column) handling * Add deleted code - This code is only used in a erpnext patch. Can be moved to that patch file * Fix codacy * Replace a mariadb specific function in a query used in validate_series * Remove a debug flag * Revert changes (rename_parent_and_child) * Fix validate_one_root method * Fix date format issue * Fix codacy - Disable a pylint for variable argument warning - Convert an instance method to static method * Add bandit.yml The Codacy seems to use Bandit which generates warning for every subprocess import and its usage during pytest Since we have carefully used subprocess (avoided user input), warnings needs to be avoided. This can be removed if we have any alternative for subprocess usage. * Skip start_process_with_partial_path check * Fix typo * Add python 2.7 test * Move python versions in travis.yml * Add python versions to jobs * Overwrite python version inheritance for postgres in travis.yml * Add quotes around python version in .travis.yml * Add quotes around the name of the job * Try a travis fix * Try .travis.yml fix * Import missing subprocess * Refactor travis.yml * Refactor travis.yml - move install and tests commands to separate files - Use matrix to build combination of python version and db type * Make install.sh and run-tests.sh executable * Add sudo required to travis.yml to allow sudo cmmands in shell files * Load nvm * Remove verbose flag from scripts * Remove command-trace-print flag * Change to build dir in before script * Add absolute path for scripts * Fix tests * Fix typo * Fix codacy - fixes - "echo won't expand escape sequences." warning * Append (_) underscore instead of 'd' for db_name * Remove printf and use mysql execute flag
6 years ago
Postgres support for Frappe (#5919) * [start] postgres * [wip] started refactoring db_schema * Add psycopg2 to requirements.txt * Add support for Postgres SQL - Separate frameworkSQL, database, schema, setup_db file for mariaDB and postgres - WIP * Remove quotes from sql to make it compatible with postgres as well * Moved some code from db_schema to database.py * Move code from db_schema to schema.py Add other required refactoring * Add schema chages * Remove redundant code in file * Add invalid column name exception class to exceptions.py * Add back tick in query wherever needed and replace ifnull with coalesce * Update get_column_description code in database.py file * Remove a print statement * Add keys to get on_duplicate query * Add bactick wherever necessary - Remove db_schema.py file * Remove DATE_SUB as it is incompatible with postgres - Fix prepare_filter_condition * Add backtick and quotes wherever necessary - Move get_database_size to frappe.db namespace - fix some left out bugs and errors * Add code to create key and unique index - added mysql and posgres in their respective database.py * Add more bacticks in queries and fix some errors - Pass keys to on_duplicate_update method - Replace MONTH with EXTRACT function - Remove DATEDIFF and CURDATE usage * Cast state value to int in toggle_two_factor_auth - since two_factor_auth has the datatype of Int * Refactor - Replace Timediff with normal arithmetic operator - Add MAX_COLUMN_LENGTH - Remove Redundant code - Add regexp character constant - Move create_help_table to database.py - Add get_full_text_search_condition method - Inherit MariaDBTable from DBTable * Replace Database instance with get_db method * Move db_manager to separate file * Refactor - Remove some unwanted code - Separate alter table code for postgres and mysql - Replace data_type with column_type in database.py * Make fulltext search changes in global_search.py * Add empty string check * Add root_password to site config * Create cli command for postgres console * Move setup of help database to setup_db.py * Add get_database_list method * Fix exception handling - Replace bad_field handler with missing_column handler * Fix tests and sql queries * Fix import error * Fix typo db -> database * Fix error with make_table in help.py * Try test for postgres * Remove pyhton 2.7 version to try postgres travis test * Add test fixes * Add db_type to the config of test_site_postgres * Enable query debug to check the reason for travis fail * Add backticks to check if the test passes * Update travis.yml - Add postgres addon * Try appending 'd_' to hash for db_name - since postgres does not support dbname starting with a number * Try adding db_type for global help to make travis work * Add print statements to debug travis failure * Enable transaction and remove debug flag * Fix help table creation query (postgres) * Fix import issue * Add some checks to prevent errors - Some doctypes used to get called even before they are created * Try fixes * Update travis config * Fix create index for help table * Remove unused code * Fix queries and update travis config * Fix ifnull replace logic (regex) * Add query fixes and code cleanup * Fix typo - get_column_description -> get_table_columns_description * Fix tests - Replace double quotes in query with single quote * Replace psycopg2 with psycopg2-binary to avoid warnings - http://initd.org/psycopg/docs/install.html#binary-install-from-pypi * Add multisql api * Add few multisql queries * Remove print statements * Remove get_fulltext_search_condition method and replace with multi query * Remove text slicing in create user * Set default for 'values' argument in multisql * Fix incorrect queries and remove few debug flags - Fix multisql bug * Force delete user to fix test - Fix Import error - Fix incorrect query * Fix query builder bug * Fix bad query * Fix query (minor) * Convert boolean text to int since is_private has datatype of int - Some query changes like removed double quotes and replace with interpolated string to pass multiple value pass in one of the query * Extend database class from an object to support python 2 * Fix query - Add quotes around value passed to the query for variable comparision * Try setting host_name for each test site - To avoid "RemoteDisconnected" error while testing data migration test - Update travis.yml to add hosts - Remove unwanted commit in setup_help_database * Set site hostname to data migration connector (in test file) - To connect the same site host * Fix duplicate entry issue - the problem is in naming series file. In previous commits I unknowingly changed a part of a series query due to which series were not getting reset * Replace few sql queries with orm methods * Fix codacy * Fix 'Doctype Sessions not found' issue * Fix bugs induced during codacy fixes * Fix Notification Test - Use ORM instead of raw sql * Set Date fallback value to 0001-01-01 - 0000-00-00 is invalid date in Postgres - 0001-01-01 works in both * Fix date filter method * Replace double quotes with single quote for literal value * Remove print statement * Replace double quotes with single * Fix tests - Replace few raw sql with ORM * Separate query for postgres - update_fields_to_fetch_query * Fix tests - replace locate with strpos for postgres * Fix tests - Skip test for datediff - convert bytes to str in escape method * Remove TestBot * Skip fieldname extraction * Replace docshare raw sql with ORM * Fix typo * Fix ancestor query test * Fix test data migration * Remove hardcoded hostname * Add default option and option list for db_type * Remove frappe.async module * Remove a debug flag from test * Fix codacy * fix import issue * Convert classmethod to static method * Convert few instance methods to static methods * Remove some unused imports * Fix codacy - Add exception type - Replace few instance methods with static methods - Remove unsued import * Fix codacy * Remove unused code * Remove some unused codes - Convert some instance methods to static function * Fix a issue with query modification * Fix add_index query * Fix query * Fix update_auth patch * Fix a issue with exception handling * Add try catch to a reload_doc * Add try-catch to file_manager_hook patch * import update_gravatar to set_user_gravatar patch * Undo all the wrong patch fixes * Fix db_setup code 😪 - previously it was not restoring db from source SQL which is why few old patched were breaking (because they were getting different schema structure) * Fix typo ! * Fix exception(is_missing_column) handling * Add deleted code - This code is only used in a erpnext patch. Can be moved to that patch file * Fix codacy * Replace a mariadb specific function in a query used in validate_series * Remove a debug flag * Revert changes (rename_parent_and_child) * Fix validate_one_root method * Fix date format issue * Fix codacy - Disable a pylint for variable argument warning - Convert an instance method to static method * Add bandit.yml The Codacy seems to use Bandit which generates warning for every subprocess import and its usage during pytest Since we have carefully used subprocess (avoided user input), warnings needs to be avoided. This can be removed if we have any alternative for subprocess usage. * Skip start_process_with_partial_path check * Fix typo * Add python 2.7 test * Move python versions in travis.yml * Add python versions to jobs * Overwrite python version inheritance for postgres in travis.yml * Add quotes around python version in .travis.yml * Add quotes around the name of the job * Try a travis fix * Try .travis.yml fix * Import missing subprocess * Refactor travis.yml * Refactor travis.yml - move install and tests commands to separate files - Use matrix to build combination of python version and db type * Make install.sh and run-tests.sh executable * Add sudo required to travis.yml to allow sudo cmmands in shell files * Load nvm * Remove verbose flag from scripts * Remove command-trace-print flag * Change to build dir in before script * Add absolute path for scripts * Fix tests * Fix typo * Fix codacy - fixes - "echo won't expand escape sequences." warning * Append (_) underscore instead of 'd' for db_name * Remove printf and use mysql execute flag
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: MIT. See LICENSE
  3. # Tree (Hierarchical) Nested Set Model (nsm)
  4. #
  5. # To use the nested set model,
  6. # use the following pattern
  7. # 1. name your parent field as "parent_item_group" if not have a property nsm_parent_field as your field name in the document class
  8. # 2. have a field called "old_parent" in your fields list - this identifies whether the parent has been changed
  9. # 3. call update_nsm(doc_obj) in the on_upate method
  10. # ------------------------------------------
  11. from typing import Iterator
  12. import frappe
  13. from frappe import _
  14. from frappe.model.document import Document
  15. from frappe.query_builder import DocType, Order
  16. from frappe.query_builder.functions import Coalesce, Max
  17. from frappe.query_builder.utils import DocType
  18. class NestedSetRecursionError(frappe.ValidationError):
  19. pass
  20. class NestedSetMultipleRootsError(frappe.ValidationError):
  21. pass
  22. class NestedSetChildExistsError(frappe.ValidationError):
  23. pass
  24. class NestedSetInvalidMergeError(frappe.ValidationError):
  25. pass
  26. # called in the on_update method
  27. def update_nsm(doc):
  28. # get fields, data from the DocType
  29. old_parent_field = "old_parent"
  30. parent_field = "parent_" + frappe.scrub(doc.doctype)
  31. if hasattr(doc, "nsm_parent_field"):
  32. parent_field = doc.nsm_parent_field
  33. if hasattr(doc, "nsm_oldparent_field"):
  34. old_parent_field = doc.nsm_oldparent_field
  35. parent, old_parent = doc.get(parent_field) or None, doc.get(old_parent_field) or None
  36. # has parent changed (?) or parent is None (root)
  37. if not doc.lft and not doc.rgt:
  38. update_add_node(doc, parent or "", parent_field)
  39. elif old_parent != parent:
  40. update_move_node(doc, parent_field)
  41. # set old parent
  42. doc.set(old_parent_field, parent)
  43. frappe.db.set_value(doc.doctype, doc.name, old_parent_field, parent or "", update_modified=False)
  44. doc.reload()
  45. def update_add_node(doc, parent, parent_field):
  46. """
  47. insert a new node
  48. """
  49. doctype = doc.doctype
  50. name = doc.name
  51. Table = DocType(doctype)
  52. # get the last sibling of the parent
  53. if parent:
  54. left, right = frappe.db.get_value(doctype, {"name": parent}, ["lft", "rgt"], for_update=True)
  55. validate_loop(doc.doctype, doc.name, left, right)
  56. else: # root
  57. right = (
  58. frappe.qb.from_(Table)
  59. .select(Coalesce(Max(Table.rgt), 0) + 1)
  60. .where(Coalesce(Table[parent_field], "") == "")
  61. .run(pluck=True)[0]
  62. )
  63. right = right or 1
  64. # update all on the right
  65. frappe.qb.update(Table).set(Table.rgt, Table.rgt + 2).where(Table.rgt >= right).run()
  66. frappe.qb.update(Table).set(Table.lft, Table.lft + 2).where(Table.lft >= right).run()
  67. if (
  68. frappe.qb.from_(Table).select("*").where((Table.lft == right) | (Table.rgt == right + 1)).run()
  69. ):
  70. frappe.throw(_("Nested set error. Please contact the Administrator."))
  71. # update index of new node
  72. frappe.qb.update(Table).set(Table.lft, right).set(Table.rgt, right + 1).where(
  73. Table.name == name
  74. ).run()
  75. return right
  76. def update_move_node(doc: Document, parent_field: str):
  77. parent: str = doc.get(parent_field)
  78. Table = DocType(doc.doctype)
  79. if parent:
  80. new_parent = (
  81. frappe.qb.from_(Table)
  82. .select(Table.lft, Table.rgt)
  83. .where(Table.name == parent)
  84. .for_update()
  85. .run(as_dict=True)[0]
  86. )
  87. validate_loop(doc.doctype, doc.name, new_parent.lft, new_parent.rgt)
  88. # move to dark side
  89. frappe.qb.update(Table).set(Table.lft, -Table.lft).set(Table.rgt, -Table.rgt).where(
  90. (Table.lft >= doc.lft) & (Table.rgt <= doc.rgt)
  91. ).run()
  92. # shift left
  93. diff = doc.rgt - doc.lft + 1
  94. frappe.qb.update(Table).set(Table.lft, Table.lft - diff).set(Table.rgt, Table.rgt - diff).where(
  95. Table.lft > doc.rgt
  96. ).run()
  97. # shift left rgts of ancestors whose only rgts must shift
  98. frappe.qb.update(Table).set(Table.rgt, Table.rgt - diff).where(
  99. (Table.lft < doc.lft) & (Table.rgt > doc.rgt)
  100. ).run()
  101. if parent:
  102. # re-query value due to computation above
  103. new_parent = (
  104. frappe.qb.from_(Table)
  105. .select(Table.lft, Table.rgt)
  106. .where(Table.name == parent)
  107. .for_update()
  108. .run(as_dict=True)[0]
  109. )
  110. # set parent lft, rgt
  111. frappe.qb.update(Table).set(Table.rgt, Table.rgt + diff).where(Table.name == parent).run()
  112. # shift right at new parent
  113. frappe.qb.update(Table).set(Table.lft, Table.lft + diff).set(Table.rgt, Table.rgt + diff).where(
  114. Table.lft > new_parent.rgt
  115. ).run()
  116. # shift right rgts of ancestors whose only rgts must shift
  117. frappe.qb.update(Table).set(Table.rgt, Table.rgt + diff).where(
  118. (Table.lft < new_parent.lft) & (Table.rgt > new_parent.rgt)
  119. ).run()
  120. new_diff = new_parent.rgt - doc.lft
  121. else:
  122. # new root
  123. max_rgt = frappe.qb.from_(Table).select(Max(Table.rgt)).run(pluck=True)[0]
  124. new_diff = max_rgt + 1 - doc.lft
  125. # bring back from dark side
  126. frappe.qb.update(Table).set(Table.lft, -Table.lft + new_diff).set(
  127. Table.rgt, -Table.rgt + new_diff
  128. ).where(Table.lft < 0).run()
  129. @frappe.whitelist()
  130. def rebuild_tree(doctype, parent_field):
  131. """
  132. call rebuild_node for all root nodes
  133. """
  134. # Check for perm if called from client-side
  135. if frappe.request and frappe.local.form_dict.cmd == "rebuild_tree":
  136. frappe.only_for("System Manager")
  137. meta = frappe.get_meta(doctype)
  138. if not meta.has_field("lft") or not meta.has_field("rgt"):
  139. frappe.throw(
  140. _("Rebuilding of tree is not supported for {}").format(frappe.bold(doctype)),
  141. title=_("Invalid Action"),
  142. )
  143. # get all roots
  144. right = 1
  145. table = DocType(doctype)
  146. column = getattr(table, parent_field)
  147. result = (
  148. frappe.qb.from_(table)
  149. .where((column == "") | (column.isnull()))
  150. .orderby(table.name, order=Order.asc)
  151. .select(table.name)
  152. ).run()
  153. frappe.db.auto_commit_on_many_writes = 1
  154. for r in result:
  155. right = rebuild_node(doctype, r[0], right, parent_field)
  156. frappe.db.auto_commit_on_many_writes = 0
  157. def rebuild_node(doctype, parent, left, parent_field):
  158. """
  159. reset lft, rgt and recursive call for all children
  160. """
  161. # the right value of this node is the left value + 1
  162. right = left + 1
  163. # get all children of this node
  164. table = DocType(doctype)
  165. column = getattr(table, parent_field)
  166. result = (frappe.qb.from_(table).where(column == parent).select(table.name)).run()
  167. for r in result:
  168. right = rebuild_node(doctype, r[0], right, parent_field)
  169. # we've got the left value, and now that we've processed
  170. # the children of this node we also know the right value
  171. frappe.db.set_value(
  172. doctype, parent, {"lft": left, "rgt": right}, for_update=False, update_modified=False
  173. )
  174. # return the right value of this node + 1
  175. return right + 1
  176. def validate_loop(doctype, name, lft, rgt):
  177. """check if item not an ancestor (loop)"""
  178. if name in frappe.get_all(
  179. doctype, filters={"lft": ["<=", lft], "rgt": [">=", rgt]}, pluck="name"
  180. ):
  181. frappe.throw(_("Item cannot be added to its own descendents"), NestedSetRecursionError)
  182. class NestedSet(Document):
  183. def __setup__(self):
  184. if self.meta.get("nsm_parent_field"):
  185. self.nsm_parent_field = self.meta.nsm_parent_field
  186. def on_update(self):
  187. update_nsm(self)
  188. self.validate_ledger()
  189. def on_trash(self, allow_root_deletion=False):
  190. if not getattr(self, "nsm_parent_field", None):
  191. self.nsm_parent_field = frappe.scrub(self.doctype) + "_parent"
  192. parent = self.get(self.nsm_parent_field)
  193. if not parent and not allow_root_deletion:
  194. frappe.throw(_("Root {0} cannot be deleted").format(_(self.doctype)))
  195. # cannot delete non-empty group
  196. self.validate_if_child_exists()
  197. self.set(self.nsm_parent_field, "")
  198. try:
  199. update_nsm(self)
  200. except frappe.DoesNotExistError:
  201. if self.flags.on_rollback:
  202. frappe.message_log.pop()
  203. else:
  204. raise
  205. def validate_if_child_exists(self):
  206. has_children = frappe.db.count(self.doctype, filters={self.nsm_parent_field: self.name})
  207. if has_children:
  208. frappe.throw(
  209. _("Cannot delete {0} as it has child nodes").format(self.name), NestedSetChildExistsError
  210. )
  211. def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"):
  212. if merge and hasattr(self, group_fname):
  213. is_group = frappe.db.get_value(self.doctype, newdn, group_fname)
  214. if self.get(group_fname) != is_group:
  215. frappe.throw(
  216. _("Merging is only possible between Group-to-Group or Leaf Node-to-Leaf Node"),
  217. NestedSetInvalidMergeError,
  218. )
  219. def after_rename(self, olddn, newdn, merge=False):
  220. if not self.nsm_parent_field:
  221. parent_field = "parent_" + self.doctype.replace(" ", "_").lower()
  222. else:
  223. parent_field = self.nsm_parent_field
  224. # set old_parent for children
  225. frappe.db.set_value(
  226. self.doctype,
  227. {"old_parent": newdn},
  228. {parent_field: newdn},
  229. update_modified=False,
  230. for_update=False,
  231. )
  232. if merge:
  233. rebuild_tree(self.doctype, parent_field)
  234. def validate_one_root(self):
  235. if not self.get(self.nsm_parent_field):
  236. if self.get_root_node_count() > 1:
  237. frappe.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError)
  238. def get_root_node_count(self):
  239. return frappe.db.count(self.doctype, {self.nsm_parent_field: ""})
  240. def validate_ledger(self, group_identifier="is_group"):
  241. if hasattr(self, group_identifier) and not bool(self.get(group_identifier)):
  242. if frappe.get_all(self.doctype, {self.nsm_parent_field: self.name, "docstatus": ("!=", 2)}):
  243. frappe.throw(
  244. _("{0} {1} cannot be a leaf node as it has children").format(_(self.doctype), self.name)
  245. )
  246. def get_ancestors(self):
  247. return get_ancestors_of(self.doctype, self.name)
  248. def get_parent(self) -> "NestedSet":
  249. """Return the parent Document."""
  250. parent_name = self.get(self.nsm_parent_field)
  251. if parent_name:
  252. return frappe.get_doc(self.doctype, parent_name)
  253. def get_children(self) -> Iterator["NestedSet"]:
  254. """Return a generator that yields child Documents."""
  255. child_names = frappe.get_list(
  256. self.doctype, filters={self.nsm_parent_field: self.name}, pluck="name"
  257. )
  258. for name in child_names:
  259. yield frappe.get_doc(self.doctype, name)
  260. def get_root_of(doctype):
  261. """Get root element of a DocType with a tree structure"""
  262. from frappe.query_builder.functions import Count
  263. from frappe.query_builder.terms import subqry
  264. Table = DocType(doctype)
  265. t1 = Table.as_("t1")
  266. t2 = Table.as_("t2")
  267. subq = frappe.qb.from_(t2).select(Count("*")).where((t2.lft < t1.lft) & (t2.rgt > t1.rgt))
  268. result = frappe.qb.from_(t1).select(t1.name).where((subqry(subq) == 0) & (t1.rgt > t1.lft)).run()
  269. return result[0][0] if result else None
  270. def get_ancestors_of(doctype, name, order_by="lft desc", limit=None):
  271. """Get ancestor elements of a DocType with a tree structure"""
  272. lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
  273. return frappe.get_all(
  274. doctype,
  275. {"lft": ["<", lft], "rgt": [">", rgt]},
  276. "name",
  277. order_by=order_by,
  278. limit_page_length=limit,
  279. pluck="name",
  280. )
  281. def get_descendants_of(doctype, name, order_by="lft desc", limit=None, ignore_permissions=False):
  282. """Return descendants of the current record"""
  283. lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
  284. if rgt - lft <= 1:
  285. return []
  286. return frappe.get_list(
  287. doctype,
  288. {"lft": [">", lft], "rgt": ["<", rgt]},
  289. "name",
  290. order_by=order_by,
  291. limit_page_length=limit,
  292. ignore_permissions=ignore_permissions,
  293. pluck="name",
  294. )