- name: Nominatim Discussions
url: https://github.com/osm-search/Nominatim/discussions
about: Ask questions, get support, share ideas and discuss with community members.
+ - name: Discussions about OpenStreetMap data
+ url: https://community.openstreetmap.org/
+ about: Ask questions about the data used by Nominatim and discuss with the OSM community.
run: |
sudo apt-get install -y -qq libboost-system-dev libboost-filesystem-dev libexpat1-dev zlib1g-dev libbz2-dev libpq-dev libproj-dev libicu-dev liblua${LUA_VERSION}-dev lua${LUA_VERSION} lua-dkjson nlohmann-json3-dev libspatialite7 libsqlite3-mod-spatialite
if [ "$FLAVOUR" == "oldstuff" ]; then
- pip3 install MarkupSafe==2.0.1 python-dotenv psycopg2==2.7.7 jinja2==2.8 psutil==5.4.2 pyicu==2.9 osmium PyYAML==5.1 sqlalchemy==1.4.31 datrie asyncpg aiosqlite
+ pip3 install MarkupSafe==2.0.1 python-dotenv jinja2==2.8 psutil==5.4.2 pyicu==2.9 osmium PyYAML==5.1 sqlalchemy==1.4.31 psycopg==3.1.7 datrie asyncpg aiosqlite
else
- sudo apt-get install -y -qq python3-icu python3-datrie python3-pyosmium python3-jinja2 python3-psutil python3-psycopg2 python3-dotenv python3-yaml
+ sudo apt-get install -y -qq python3-icu python3-datrie python3-pyosmium python3-jinja2 python3-psutil python3-dotenv python3-yaml
pip3 install sqlalchemy psycopg aiosqlite
fi
shell: bash
- name: Unpack Nominatim
run: tar xf nominatim-src.tar.bz2
- - uses: actions/setup-python@v4
+ - uses: actions/setup-python@v5
with:
python-version: 3.7
if: matrix.flavour == 'oldstuff'
flavour: ${{ matrix.flavour }}
lua: ${{ matrix.lua }}
- - name: Install test prerequsites (behave from apt)
+ - name: Install test prerequisites (behave from apt)
run: sudo apt-get install -y -qq python3-behave
if: matrix.flavour == 'ubuntu-20'
- - name: Install test prerequsites (behave from pip)
+ - name: Install test prerequisites (behave from pip)
run: pip3 install behave==1.2.6
if: (matrix.flavour == 'oldstuff') || (matrix.flavour == 'ubuntu-22')
- - name: Install test prerequsites (from apt for Ununtu 2x)
+ - name: Install test prerequisites (from apt for Ununtu 2x)
run: sudo apt-get install -y -qq python3-pytest python3-pytest-asyncio uvicorn
if: matrix.flavour != 'oldstuff'
run: pip3 install -U pytest-asyncio
if: matrix.flavour == 'ubuntu-20'
- - name: Install test prerequsites (from pip for Ubuntu 18)
+ - name: Install test prerequisites (from pip for Ubuntu 18)
run: pip3 install pytest pytest-asyncio uvicorn
if: matrix.flavour == 'oldstuff'
- name: Install latest pylint
run: pip3 install -U pylint
- if: matrix.flavour != 'oldstuff'
+ if: matrix.flavour == 'ubuntu-22'
- name: Python linting
- run: python3 -m pylint nominatim
+ run: python3 -m pylint src
working-directory: Nominatim
- if: matrix.flavour != 'oldstuff'
+ if: matrix.flavour == 'ubuntu-22'
- name: Python unit tests
run: python3 -m pytest test/python
- name: BDD tests
run: |
- python3 -m behave -DREMOVE_TEMPLATE=1 -DBUILDDIR=$GITHUB_WORKSPACE/build --format=progress3
+ export PATH=$GITHUB_WORKSPACE/build/osm2pgsql:$PATH
+ python3 -m behave -DREMOVE_TEMPLATE=1 --format=progress3
working-directory: Nominatim/test/bdd
- name: Install mypy and typechecking info
if: matrix.flavour != 'oldstuff'
- name: Python static typechecking
- run: python3 -m mypy --strict nominatim
+ run: python3 -m mypy --strict src
working-directory: Nominatim
if: matrix.flavour != 'oldstuff'
with:
cmake-args: -DBUILD_MODULE=on
- - name: Install test prerequsites
+ - name: Install test prerequisites
run: sudo apt-get install -y -qq python3-behave
- name: BDD tests (legacy tokenizer)
run: |
- python3 -m behave -DREMOVE_TEMPLATE=1 -DBUILDDIR=$GITHUB_WORKSPACE/build -DAPI_ENGINE=php -DTOKENIZER=legacy --format=progress3
+ export PATH=$GITHUB_WORKSPACE/build/osm2pgsql:$PATH
+ python3 -m behave -DREMOVE_TEMPLATE=1 -DSERVER_MODULE_PATH=$GITHUB_WORKSPACE/build/module -DAPI_ENGINE=php -DTOKENIZER=legacy --format=progress3
working-directory: Nominatim/test/bdd
with:
flavour: 'ubuntu-22'
- - name: Install test prerequsites
+ - name: Install test prerequisites
run: sudo apt-get install -y -qq python3-behave
- name: BDD tests (php)
run: |
- python3 -m behave -DREMOVE_TEMPLATE=1 -DBUILDDIR=$GITHUB_WORKSPACE/build -DAPI_ENGINE=php --format=progress3
+ export PATH=$GITHUB_WORKSPACE/build/osm2pgsql:$PATH
+ python3 -m behave -DREMOVE_TEMPLATE=1 -DAPI_ENGINE=php --format=progress3
working-directory: Nominatim/test/bdd
strategy:
matrix:
- name: [Ubuntu-20, Ubuntu-22]
+ name: [Ubuntu-22, Ubuntu-24]
include:
- - name: Ubuntu-20
- image: "ubuntu:20.04"
- ubuntu: 20
- install_mode: install-apache
- name: Ubuntu-22
image: "ubuntu:22.04"
ubuntu: 22
install_mode: install-apache
+ - name: Ubuntu-24
+ image: "ubuntu:24.04"
+ ubuntu: 24
+ install_mode: install-apache
container:
image: ${{ matrix.image }}
mkdir data-env-reverse
working-directory: /home/nominatim
+ - name: Add nominatim to path
+ run: |
+ sudo ln -s /home/nominatim/nominatim-venv/bin/nominatim /usr/local/bin/nominatim
+ if: matrix.ubuntu == 24
+
+ - name: Need lua binary
+ run: |
+ sudo apt-get install -y lua5.4 lua-dkjson
+ if: matrix.ubuntu == 24
+
- name: Print version
run: nominatim --version
working-directory: /home/nominatim/nominatim-project
run: apt-get install -y python3-pip
shell: bash
- - name: Run update
+ - name: Install osmium (Ubuntu 22)
run: |
pip3 install --user osmium
+ if: matrix.ubuntu == 22
+
+ - name: Install osmium (Ubuntu 24)
+ run: |
+ /home/nominatim/nominatim-venv/bin/pip install osmium
+ if: matrix.ubuntu == 24
+
+ - name: Run update
+ run: |
nominatim replication --init
NOMINATIM_REPLICATION_MAX_DIFF=1 nominatim replication --once
working-directory: /home/nominatim/nominatim-project
*.log
*.pyc
+*.swp
docs/develop/*.png
+site-html
build
+dist
+.coverage
.vagrant
data/country_osm_grid.sql.gz
disable=too-few-public-methods,duplicate-code,too-many-ancestors,bad-option-value,no-self-use,not-context-manager,use-dict-literal,chained-comparison,attribute-defined-outside-init,too-many-boolean-expressions,contextmanager-generator-missing-cleanup
good-names=i,j,x,y,m,t,fd,db,cc,x1,x2,y1,y2,pt,k,v,nr
+
+[DESIGN]
+
+max-returns=7
\ No newline at end of file
set(BUILD_API on CACHE BOOL "Build everything for the API server")
set(BUILD_MODULE off CACHE BOOL "Build PostgreSQL module for legacy tokenizer")
set(BUILD_TESTS on CACHE BOOL "Build test suite")
-set(BUILD_DOCS on CACHE BOOL "Build documentation")
-set(BUILD_MANPAGE on CACHE BOOL "Build Manual Page")
set(BUILD_OSM2PGSQL on CACHE BOOL "Build osm2pgsql (expert only)")
set(INSTALL_MUNIN_PLUGINS on CACHE BOOL "Install Munin plugins for supervising Nominatim")
# python (imports/updates only)
#-----------------------------------------------------------------------------
-if (BUILD_IMPORTER)
+if (BUILD_IMPORTER OR BUILD_API)
find_package(PythonInterp 3.7 REQUIRED)
endif()
add_subdirectory(module)
endif()
-#-----------------------------------------------------------------------------
-# Documentation
-#-----------------------------------------------------------------------------
-
-if (BUILD_DOCS)
- add_subdirectory(docs)
-endif()
-
-#-----------------------------------------------------------------------------
-# Manual page
-#-----------------------------------------------------------------------------
-
-if (BUILD_MANPAGE)
- add_subdirectory(man)
-endif()
-
#-----------------------------------------------------------------------------
# Installation
#-----------------------------------------------------------------------------
DESTINATION ${CMAKE_INSTALL_BINDIR}
RENAME nominatim)
- install(DIRECTORY nominatim
- DESTINATION ${NOMINATIM_LIBDIR}/lib-python
- FILES_MATCHING PATTERN "*.py"
- PATTERN "paths.py" EXCLUDE
- PATTERN __pycache__ EXCLUDE)
-
if (EXISTS ${PHP_BIN})
configure_file(${PROJECT_SOURCE_DIR}/cmake/paths-py.tmpl paths-py.installed)
else()
configure_file(${PROJECT_SOURCE_DIR}/cmake/paths-py-no-php.tmpl paths-py.installed)
endif()
- install(FILES ${PROJECT_BINARY_DIR}/paths-py.installed
- DESTINATION ${NOMINATIM_LIBDIR}/lib-python/nominatim
- RENAME paths.py)
+
+ foreach (submodule nominatim_db nominatim_api)
+ install(DIRECTORY src/${submodule}
+ DESTINATION ${NOMINATIM_LIBDIR}/lib-python
+ FILES_MATCHING PATTERN "*.py"
+ PATTERN "paths.py" EXCLUDE
+ PATTERN __pycache__ EXCLUDE)
+ install(FILES ${PROJECT_BINARY_DIR}/paths-py.installed
+ DESTINATION ${NOMINATIM_LIBDIR}/lib-python/${submodule}
+ RENAME paths.py)
+ endforeach()
install(DIRECTORY lib-sql DESTINATION ${NOMINATIM_LIBDIR})
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+GNU GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007
-Also add information on how to contact you by electronic and paper mail.
+Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+Preamble
+
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
+
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
+
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and modification follow.
+
+TERMS AND CONDITIONS
+
+0. Definitions.
+
+“This License” refers to version 3 of the GNU General Public License.
+
+“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
+
+“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
+
+To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
+
+A “covered work” means either the unmodified Program or a work based on the Program.
+
+To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
+
+To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
+
+1. Source Code.
+The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
+
+A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
+
+The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
+
+The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same work.
+
+2. Basic Permissions.
+All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
+
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
+
+When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
+
+4. Conveying Verbatim Copies.
+You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
+
+5. Conveying Modified Source Versions.
+You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
+
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
+
+A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
+
+6. Conveying Non-Source Forms.
+You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
+
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
+
+A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
+“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
+If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
+
+The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
+
+7. Additional Terms.
+“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
+
+All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
+
+8. Termination.
+You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
+
+However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
+
+Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
+
+9. Acceptance Not Required for Having Copies.
+You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
+
+10. Automatic Licensing of Downstream Recipients.
+Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
+
+An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
+
+11. Patents.
+A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
+
+A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
+
+In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
+
+A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
+
+12. No Surrender of Others' Freedom.
+If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
+
+13. Use with the GNU Affero General Public License.
+Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
+
+14. Revised Versions of this License.
+The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
+
+Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
+
+15. Disclaimer of Warranty.
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. Limitation of Liability.
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+17. Interpretation of Sections 15 and 16.
+If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
+If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
+The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
+You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
+The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
--- /dev/null
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
--- /dev/null
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
--- /dev/null
+all:
+
+# Building of wheels
+
+build: clean-build build-db build-api
+
+clean-build:
+ rm -f dist/*
+
+build-db:
+ python3 -m build packaging/nominatim-db --outdir dist/
+
+build-api:
+ python3 -m build packaging/nominatim-api --outdir dist/
+
+# Tests
+
+tests: mypy lint pytest bdd
+
+mypy:
+ mypy --strict src
+
+pytest:
+ pytest test/python
+
+lint:
+ pylint src
+
+bdd:
+ cd test/bdd; behave -DREMOVE_TEMPLATE=1
+
+# Documentation
+
+doc:
+ mkdocs build
+
+serve-doc:
+ mkdocs serve
+
+manpage:
+ argparse-manpage --pyfile man/create-manpage.py --function get_parser --project-name Nominatim --url https://nominatim.org > man/nominatim.1 --author 'the Nominatim developer community' --author-email info@nominatim.org
+
+
+.PHONY: tests mypy pytest lint bdd build clean-build build-db build-api doc serve-doc manpage
[![Build Status](https://github.com/osm-search/Nominatim/workflows/CI%20Tests/badge.svg)](https://github.com/osm-search/Nominatim/actions?query=workflow%3A%22CI+Tests%22)
-[![codecov](https://codecov.io/gh/osm-search/Nominatim/branch/master/graph/badge.svg?token=8P1LXrhCMy)](https://codecov.io/gh/osm-search/Nominatim)
Nominatim
=========
License
=======
-The source code is available under a GPLv2 license.
+The Python source code is available under a GPL license version 3 or later.
+The Lua configuration files for osm2pgsql are released under the
+Apache License, Version 2.0. All other files are under a GPLv2 license.
Contributing
============
-Contributions, bugreport and pull requests are welcome.
-For details see [contribution guide](CONTRIBUTING.md).
+Contributions, bug reports and pull requests are welcome. When reporting a
+bug, please use one of the
+[issue templates](https://github.com/osm-search/Nominatim/issues/new/choose)
+and make sure to provide all the information requested. If you are not
+sure if you have really found a bug, please ask for help in the forums
+first (see 'Questions' below).
+
+For details on contributing, have a look at the
+[contribution guide](CONTRIBUTING.md).
Questions and help
==================
-For questions, community help and discussions you can use the
-[Github discussions forum](https://github.com/osm-search/Nominatim/discussions)
-or join the
-[geocoding mailing list](https://lists.openstreetmap.org/listinfo/geocoding).
+If you have questions about search results and the OpenStreetMap data
+used in the search, use the [OSM Forum](https://community.openstreetmap.org/).
+
+For questions, community help and discussions around the software and
+your own installation of Nominatim, use the
+[Github discussions forum](https://github.com/osm-search/Nominatim/discussions).
end
end
+ config.vm.provider "parallels" do |prl, override|
+ prl.update_guest_tools = false
+ prl.memory = 2048
+ if ENV['CHECKOUT'] != 'y' then
+ override.vm.synced_folder ".", "/home/vagrant/Nominatim"
+ end
+ end
+
config.vm.provider "libvirt" do |lv, override|
lv.memory = 2048
lv.nested = true
config.vm.define "ubuntu22", primary: true do |sub|
sub.vm.box = "generic/ubuntu2204"
+ if RUBY_PLATFORM.include?('darwin') && RUBY_PLATFORM.include?('arm64')
+ # Apple M processor
+ sub.vm.box = 'luminositylabsllc/ubuntu-22.04-arm64'
+ end
sub.vm.provision :shell do |s|
s.path = "vagrant/Install-on-Ubuntu-22.sh"
s.privileged = false
end
end
- config.vm.define "ubuntu20" do |sub|
- sub.vm.box = "generic/ubuntu2004"
+ config.vm.define "ubuntu24" do |sub|
+ sub.vm.box = "bento/ubuntu-24.04"
sub.vm.provision :shell do |s|
- s.path = "vagrant/Install-on-Ubuntu-20.sh"
+ s.path = "vagrant/Install-on-Ubuntu-24.sh"
s.privileged = false
s.args = [checkout]
end
end
- config.vm.define "ubuntu20-apache" do |sub|
- sub.vm.box = "generic/ubuntu2004"
+ config.vm.define "ubuntu24-apache" do |sub|
+ sub.vm.box = "bento/ubuntu-24.04"
sub.vm.provision :shell do |s|
- s.path = "vagrant/Install-on-Ubuntu-20.sh"
+ s.path = "vagrant/Install-on-Ubuntu-24.sh"
s.privileged = false
s.args = [checkout, "install-apache"]
end
end
- config.vm.define "ubuntu20-nginx" do |sub|
- sub.vm.box = "generic/ubuntu2004"
+ config.vm.define "ubuntu24-nginx" do |sub|
+ sub.vm.box = "bento/ubuntu-24.04"
sub.vm.provision :shell do |s|
- s.path = "vagrant/Install-on-Ubuntu-20.sh"
+ s.path = "vagrant/Install-on-Ubuntu-24.sh"
s.privileged = false
s.args = [checkout, "install-nginx"]
end
sys.path.insert(1, '@NOMINATIM_LIBDIR@/lib-python')
-from nominatim import cli
-from nominatim import version
+from nominatim_db import cli
+from nominatim_db import version
version.GIT_COMMIT_HASH = '@GIT_HASH@'
import sys
import os
-sys.path.insert(1, '@CMAKE_SOURCE_DIR@')
+sys.path.insert(1, '@CMAKE_SOURCE_DIR@/src')
-from nominatim import cli
-from nominatim import version
+from nominatim_db import cli
+from nominatim_db import version
version.GIT_COMMIT_HASH = '@GIT_HASH@'
+++ /dev/null
-# Auto-generated vagrant install documentation
-
-
-# build the actual documentation
-
-configure_file(mkdocs.yml ../mkdocs.yml)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/appendix)
-
-set (DOC_SOURCES
- admin
- develop
- api
- customize
- library
- index.md
- extra.css
- styles.css
- )
-
-foreach (src ${DOC_SOURCES})
- execute_process(
- COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_CURRENT_SOURCE_DIR}/${src} ${CMAKE_CURRENT_BINARY_DIR}/${src}
- )
-endforeach()
-
-ADD_CUSTOM_TARGET(doc
- COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/bash2md.sh ${PROJECT_SOURCE_DIR}/vagrant/Install-on-Ubuntu-20.sh ${CMAKE_CURRENT_BINARY_DIR}/appendix/Install-on-Ubuntu-20.md
- COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/bash2md.sh ${PROJECT_SOURCE_DIR}/vagrant/Install-on-Ubuntu-22.sh ${CMAKE_CURRENT_BINARY_DIR}/appendix/Install-on-Ubuntu-22.md
- COMMAND mkdocs build -d ${CMAKE_CURRENT_BINARY_DIR}/../site-html -f ${CMAKE_CURRENT_BINARY_DIR}/../mkdocs.yml
-)
-
-ADD_CUSTOM_TARGET(serve-doc
- COMMAND mkdocs serve -f ${CMAKE_CURRENT_BINARY_DIR}/../mkdocs.yml
- WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
-)
PostgreSQL module that was compiled on your target machine. If you get errors
that PostgreSQL cannot find or access `nominatim.so` then rerun
- nominatim refresh --functions
+ nominatim refresh --functions
on the target machine to update the the location of the module.
# Deploying the Nominatim Python frontend
-The Nominatim can be run as a Python-based
+Nominatim can be run as a Python-based
[ASGI web application](https://asgi.readthedocs.io/en/latest/). You have the
choice between [Falcon](https://falcon.readthedocs.io/en/stable/)
and [Starlette](https://www.starlette.io/) as the ASGI framework.
!!! Note
Throughout this page, we assume your Nominatim project directory is
- located in `/srv/nominatim-project` and you have installed Nominatim
- using the default installation prefix `/usr/local`. If you have put it
- somewhere else, you need to adjust the commands and configuration
- accordingly.
+ located in `/srv/nominatim-project`. If you have put it somewhere else,
+ you need to adjust the commands and configuration accordingly.
- We further assume that your web server runs as user `www-data`. Older
- versions of CentOS may still use the user name `apache`. You also need
- to adapt the instructions in this case.
### Installing the required packages
+The Nominatim frontend is best run from its own virtual environment. If
+you have already created one for the database backend during the
+[installation](Installation.md#building-nominatim), you can use that. Otherwise
+create one now with:
+
+```sh
+sudo apt-get install virtualenv
+virtualenv /srv/nominatim-venv
+```
+
+The Nominatim frontend is contained in the 'nominatim-api' package. To
+install directly from the source tree run:
+
+```sh
+cd Nominatim
+/srv/nominatim-venv/bin/pip install packaging/nominatim-api
+```
+
The recommended way to deploy a Python ASGI application is to run
the ASGI runner [uvicorn](https://uvicorn.org/)
together with [gunicorn](https://gunicorn.org/) HTTP server. We use
Falcon here as the web framework.
-Create a virtual environment for the Python packages and install the necessary
-dependencies:
+Add the necessary packages to your virtual environment:
``` sh
-sudo apt install virtualenv
-virtualenv /srv/nominatim-venv
-/srv/nominatim-venv/bin/pip install SQLAlchemy PyICU psycopg[binary] \
- psycopg2-binary python-dotenv PyYAML falcon uvicorn gunicorn
+/srv/nominatim-venv/bin/pip install falcon uvicorn gunicorn
```
### Setting up Nominatim as a systemd job
[Service]
Type=simple
-Environment="PYTHONPATH=/usr/local/lib/nominatim/lib-python/"
User=www-data
Group=www-data
WorkingDirectory=/srv/nominatim-project
-ExecStart=/srv/nominatim-venv/bin/gunicorn -b unix:/run/nominatim.sock -w 4 -k uvicorn.workers.UvicornWorker nominatim.server.falcon.server:run_wsgi
+ExecStart=/srv/nominatim-venv/bin/gunicorn -b unix:/run/nominatim.sock -w 4 -k uvicorn.workers.UvicornWorker nominatim_api.server.falcon.server:run_wsgi
ExecReload=/bin/kill -s HUP $MAINPID
StandardOutput=append:/var/log/gunicorn-nominatim.log
StandardError=inherit
See the installation instructions for a full list of required packages.
+### UnicodeEncodeError: 'ascii' codec can't encode character
+
+Make sure that the operating system's locale is UTF-8. With some prebuilt
+images (e.g. LXC containers from Proxmox, see
+[discussion](https://github.com/osm-search/Nominatim/discussions/2343)) or
+images that optimize for size it might be missing.
+
+On Ubuntu you can check the locale is installed:
+
+```
+ grep UTF-8 /etc/default/locale
+```
+
+And install it using
+
+```
+ dpkg-reconfigure locales
+```
+
### I forgot to delete the flatnodes file before starting an import.
That's fine. For each import the flatnodes file get overwritten.
This data is available as a binary download. Put it into your project directory:
cd $PROJECT_DIR
- wget https://nominatim.org/data/wikimedia-importance.sql.gz
+ wget https://nominatim.org/data/wikimedia-importance.csv.gz
wget -O secondary_importance.sql.gz https://nominatim.org/data/wikimedia-secondary-importance.sql.gz
The files are about 400MB and add around 4GB to the Nominatim database. For
prerequisites. There are also step-by-step instructions available for
the following operating systems:
- * [Ubuntu 22.04](../appendix/Install-on-Ubuntu-22.md)
- * [Ubuntu 20.04](../appendix/Install-on-Ubuntu-20.md)
+ * [Ubuntu 24.04](Install-on-Ubuntu-24.md)
+ * [Ubuntu 22.04](Install-on-Ubuntu-22.md)
These OS-specific instructions can also be found in executable form
in the `vagrant/` directory.
otherwise import and queries will be slow to the point of being unusable.
Query performance has marked improvements with PostgreSQL 13+ and PostGIS 3.2+.
-For compiling:
-
- * [cmake](https://cmake.org/)
- * [expat](https://libexpat.github.io/)
- * [proj](https://proj.org/)
- * [bzip2](http://www.bzip.org/)
- * [zlib](https://www.zlib.net/)
- * [ICU](http://site.icu-project.org/)
- * [nlohmann/json](https://json.nlohmann.me/)
- * [Boost libraries](https://www.boost.org/), including system and filesystem
- * PostgreSQL client libraries
- * a recent C++ compiler (gcc 5+ or Clang 3.8+)
-
For running Nominatim:
* [PostgreSQL](https://www.postgresql.org) (9.6+ will work, 11+ strongly recommended)
* [PostGIS](https://postgis.net) (2.2+ will work, 3.0+ strongly recommended)
+ * [osm2pgsql](https://osm2pgsql.org) (1.8+, optional when building with CMake)
* [Python 3](https://www.python.org/) (3.7+)
- * [Psycopg2](https://www.psycopg.org) (2.7+)
+
+Furthermore the following Python libraries are required:
+
+ * [Psycopg3](https://www.psycopg.org)
* [Python Dotenv](https://github.com/theskumar/python-dotenv)
* [psutil](https://github.com/giampaolo/psutil)
* [Jinja2](https://palletsprojects.com/p/jinja/)
- * [SQLAlchemy](https://www.sqlalchemy.org/) (1.4.31+ with greenlet support)
- * [asyncpg](https://magicstack.github.io/asyncpg) (0.8+)
* [PyICU](https://pypi.org/project/PyICU/)
* [PyYaml](https://pyyaml.org/) (5.1+)
* [datrie](https://github.com/pytries/datrie)
+These will be installed automatically when using pip installation.
+
+When using legacy CMake-based installation:
+
+ * [cmake](https://cmake.org/)
+ * [expat](https://libexpat.github.io/)
+ * [proj](https://proj.org/)
+ * [bzip2](http://www.bzip.org/)
+ * [zlib](https://www.zlib.net/)
+ * [ICU](http://site.icu-project.org/)
+ * [nlohmann/json](https://json.nlohmann.me/)
+ * [Boost libraries](https://www.boost.org/), including system and file system
+ * PostgreSQL client libraries
+ * a recent C++ compiler (gcc 5+ or Clang 3.8+)
+
For running continuous updates:
* [pyosmium](https://osmcode.org/pyosmium/)
For running the Python frontend:
+ * [SQLAlchemy](https://www.sqlalchemy.org/) (1.4.31+ with greenlet support)
+ * [asyncpg](https://magicstack.github.io/asyncpg) (0.8+, only when using SQLAlchemy < 2.0)
* one of the following web frameworks:
* [falcon](https://falconframework.org/) (3.0+)
* [starlette](https://www.starlette.io/)
Fast disks are essential. Using NVME disks is recommended.
Even on a well configured machine the import of a full planet takes
-around 2 days. When using traditional SSDs, 4-5 days are more realistic.
+around 2.5 days. When using traditional SSDs, 4-5 days are more realistic.
## Tuning the PostgreSQL database
maintenance_work_mem = (10GB)
autovacuum_work_mem = 2GB
work_mem = (50MB)
- effective_cache_size = (24GB)
synchronous_commit = off
max_wal_size = 1GB
- checkpoint_timeout = 10min
+ checkpoint_timeout = 60min
checkpoint_completion_target = 0.9
+ random_page_cost = 1.0
+ wal_level = minimal
+ max_wal_senders = 0
The numbers in brackets behind some parameters seem to work fine for
-64GB RAM machine. Adjust to your setup. A higher number for `max_wal_size`
+128GB RAM machine. Adjust to your setup. A higher number for `max_wal_size`
means that PostgreSQL needs to run checkpoints less often but it does require
the additional space on your disk.
### Building Nominatim
+#### Building the latest development version with pip
+
+Nominatim is easiest to run from its own virtual environment. To create one, run:
+
+ sudo apt-get install virtualenv
+ virtualenv /srv/nominatim-venv
+
+To install Nominatim directly from the source tree into the virtual environment, run:
+
+ /srv/nominatim-venv/bin/pip install packaging/nominatim-{db,api}
+
+#### Building in legacy CMake mode
+
+!!! warning
+ Installing Nominatim through CMake is now deprecated. The infrastructure
+ will be removed in Nominatim 5.0. Please switch to pip installation.
+
The code must be built in a separate directory. Create the directory and
change into it.
If you are migrating from a version <3.6, then you still have to follow
the manual migration steps up to 3.6.
+## 4.4.0 -> master
+
+### New structure for Python packages
+
+The nominatim Python package has been split into `nominatim-db` and `nominatim-api`.
+Any imports need to be adapted accordingly.
+
+If you are running the Python frontend, change the server module from
+`nominatim.server.falcon.server` to `nominatim_api.server.falcon.server`.
+
+If you are using the Nominatim library, all imports need to be changed
+from `nominatim.api.<module>` to `nominatim_api.<module>`.
+
+If you have written custom tokenizers or sanitizers, the appropriate modules
+are now found in `nominatim_db`.
+
## 4.2.0 -> 4.3.0
### New indexes for reverse lookup
results when using Nominatim in the browser versus in a command-line tool
like wget or curl. The command-line tools
usually don't send any Accept-Language header, prompting Nominatim
- to show results in the local language. Browsers on the contratry always
+ to show results in the local language. Browsers on the contrary always
send the currently chosen browser language.
results when using Nominatim in the browser versus in a command-line tool
like wget or curl. The command-line tools
usually don't send any Accept-Language header, prompting Nominatim
- to show results in the local language. Browsers on the contratry always
+ to show results in the local language. Browsers on the contrary always
send the currently chosen browser language.
results when using Nominatim in the browser versus in a command-line tool
like wget or curl. The command-line tools
usually don't send any Accept-Language header, prompting Nominatim
- to show results in the local language. Browsers on the contratry always
+ to show results in the local language. Browsers on the contrary always
send the currently chosen browser language.
### Result restriction
|-----------| ----- | ------- |
| countrycodes | comma-separated list of country codes | _unset_ |
-Filer that limits the search results to one or more countries.
+Filter that limits the search results to one or more countries.
The country code must be the
[ISO 3166-1alpha2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) code
of the country, e.g. `gb` for the United Kingdom, `de` for Germany.
+++ /dev/null
-#!/bin/sh
-#
-# Extract markdown-formatted documentation from a source file
-#
-# Usage: bash2md.sh <infile> <outfile>
-
-sed '/^#!/d;s:^#\( \|$\)::;s/.*#DOCS://' $1 > $2
and for [secondary importance](https://nominatim.org/data/wikimedia-secondary-importance.sql.gz)
based on Wikipedia importance of the administrative areas.
-The source code for creating these files is avaible in the Github projects
+The source code for creating these files is available in the Github projects
[osm-search/wikipedia-wikidata](https://github.com/osm-search/wikipedia-wikidata)
and
[osm-search/secondary-importance](https://github.com/osm-search/secondary-importance).
* **phrase**: the keyword to look for
* **class**: key of the main tag of the place to find
- (see [principal tags in import style](../Import-Styles.md#set_main_tags-principal-tags)
+ (see [principal tags in import style](Import-Styles.md#set_main_tags-principal-tags)
* **type**: value of the main tag
* **operator**: type of special phrase, may be one of:
* *in*: place is within the place defined by the search term (e.g. "_Hotels in_ Berlin")
```
This is in particular useful when the database runs on a different server.
-See [Advanced installations](../admin/Advanced-Installations.md#importing-nominatim-to-an-external-postgresql-database) for details.
+See [Advanced installations](../admin/Advanced-Installations.md#using-an-external-postgresql-database) for details.
There are no other configuration options for the legacy tokenizer. All
normalization functions are hard-coded.
##### split-name-list
-::: nominatim.tokenizer.sanitizers.split_name_list
+::: nominatim_db.tokenizer.sanitizers.split_name_list
options:
members: False
heading_level: 6
##### strip-brace-terms
-::: nominatim.tokenizer.sanitizers.strip_brace_terms
+::: nominatim_db.tokenizer.sanitizers.strip_brace_terms
options:
members: False
heading_level: 6
##### tag-analyzer-by-language
-::: nominatim.tokenizer.sanitizers.tag_analyzer_by_language
+::: nominatim_db.tokenizer.sanitizers.tag_analyzer_by_language
options:
members: False
heading_level: 6
##### clean-housenumbers
-::: nominatim.tokenizer.sanitizers.clean_housenumbers
+::: nominatim_db.tokenizer.sanitizers.clean_housenumbers
options:
members: False
heading_level: 6
##### clean-postcodes
-::: nominatim.tokenizer.sanitizers.clean_postcodes
+::: nominatim_db.tokenizer.sanitizers.clean_postcodes
options:
members: False
heading_level: 6
##### clean-tiger-tags
-::: nominatim.tokenizer.sanitizers.clean_tiger_tags
+::: nominatim_db.tokenizer.sanitizers.clean_tiger_tags
options:
members: False
heading_level: 6
#### delete-tags
-::: nominatim.tokenizer.sanitizers.delete_tags
+::: nominatim_db.tokenizer.sanitizers.delete_tags
options:
members: False
heading_level: 6
#### tag-japanese
-::: nominatim.tokenizer.sanitizers.tag_japanese
+::: nominatim_db.tokenizer.sanitizers.tag_japanese
options:
members: False
heading_level: 6
and how to run tests.
!!! Important
- This guide assumes that you develop under the latest version of Ubuntu. You
- can of course also use your favourite distribution. You just might have to
- adapt the commands below slightly, in particular the commands for installing
- additional software.
+ This guide assumes you develop under the latest version of Debian/Ubuntu.
+ You can of course also use your favourite distribution. You just might have
+ to adapt the commands below slightly, in particular the commands for
+ installing additional software.
## Installing Nominatim
The first step is to install Nominatim itself. Please follow the installation
instructions in the [Admin section](../admin/Installation.md). You don't need
-to set up a webserver for development, the webserver that is included with PHP
-is sufficient.
+to set up a webserver for development, the webserver that can be started
+via `nominatim serve` is sufficient.
-If you want to run Nominatim in a VM via Vagrant, use the default `ubuntu` setup.
+If you want to run Nominatim in a VM via Vagrant, use the default `ubuntu24` setup.
Vagrant's libvirt provider runs out-of-the-box under Ubuntu. You also need to
install an NFS daemon to enable directory sharing between host and guest. The
following packages should get you started:
For testing the Python search frontend, you need to install extra dependencies
depending on your choice of webserver framework:
-* [httpx](https://www.python-httpx.org/) (starlette only)
-* [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan) (starlette only)
+* [httpx](https://www.python-httpx.org/) (Starlette only)
+* [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan) (Starlette only)
The documentation is built with mkdocs:
* [mkdocs](https://www.mkdocs.org/) >= 1.1.2
-* [mkdocstrings](https://mkdocstrings.github.io/) >= 0.18
-* [mkdocstrings-python](https://mkdocstrings.github.io/python/)
+* [mkdocstrings](https://mkdocstrings.github.io/) >= 0.25
+* [mkdocs-material](https://squidfunk.github.io/mkdocs-material/)
+* [mkdocs-gen-files](https://oprypin.github.io/mkdocs-gen-files/)
+
+Please be aware that tests always run against the globally installed
+osm2pgsql, so you need to have this set up. If you want to test against
+the vendored version of osm2pgsql, you need to set the PATH accordingly.
### Installing prerequisites on Ubuntu/Debian
-Some of the Python packages require the newest version which is not yet
-available with the current distributions. Therefore it is recommended to
-install pip to get the newest versions.
+The Python tools should always be run with the most recent version.
+In particular, pylint tends to have a lot of breaking changes between versions.
+The easiest way, to handle these Python dependencies is to run your
+development from within a virtual environment.
-To install all necessary packages run:
+To set up the virtual environment with all necessary packages run:
```sh
-sudo apt install php-cgi phpunit php-codesniffer \
- python3-pip python3-setuptools python3-dev
-
-pip3 install --user behave mkdocs mkdocstrings pytest pytest-asyncio pylint \
- mypy types-PyYAML types-jinja2 types-psycopg2 types-psutil \
- types-ujson types-requests types-Pygments typing-extensions\
- httpx asgi-lifespan
+virtualenv ~/nominatim-dev-venv
+~/nominatim-dev-venv/bin/pip install\
+ psutil psycopg[binary] PyICU SQLAlchemy \
+ python-dotenv jinja2 pyYAML datrie behave \
+ mkdocs mkdocstrings mkdocs-gen-files pytest pytest-asyncio pylint \
+ types-jinja2 types-markupsafe types-psutil types-psycopg2 \
+ types-pygments types-pyyaml types-requests types-ujson \
+ types-urllib3 typing-extensions unicorn falcon
```
-The `mkdocs` executable will be located in `.local/bin`. You may have to add
-this directory to your path, for example by running:
+Now enter the virtual environment whenever you want to develop:
+```sh
+. ~/nominatim-dev-venv/bin/activate
```
-echo 'export PATH=~/.local/bin:$PATH' > ~/.profile
+
+For installing the PHP development tools, run:
+
+```sh
+sudo apt install php-cgi phpunit php-codesniffer
```
If your distribution does not have PHPUnit 7.3+, you can install it (as well
```
The binaries are found in `.config/composer/vendor/bin`. You need to add this
-to your PATH as well:
+to your PATH:
```
echo 'export PATH=~/.config/composer/vendor/bin:$PATH' > ~/.profile
```
+### Running Nominatim during development
+
+The source code for Nominatim can be found in the `src` directory and can
+be run in-place. The source directory features a special script
+`nominatim-cli.py` which does the same as the installed 'nominatim' binary
+but executes against the code in the source tree. For example:
+
+```
+me@machine:~$ cd Nominatim
+me@machine:~Nominatim$ ./nominatim-cli.py --version
+Nominatim version 4.4.99-1
+```
+
+Make sure you have activated the virtual environment holding all
+necessary dependencies.
## Executing Tests
All tests are located in the `/test` directory.
-To run all tests just go to the build directory and run make:
+To run all tests, run make from the source root:
+
+```sh
+make tests
+```
+
+There are also make targets for executing only parts of the test suite.
+For example to run linting only use:
```sh
-cd build
-make test
+make lint
```
+The possible testing targets are: mypy, lint, pytest, bdd.
+
For more information about the structure of the tests and how to change and
extend the test suite, see the [Testing chapter](Testing.md).
framework. The master branch is automatically deployed every night on
[https://nominatim.org/release-docs/develop/](https://nominatim.org/release-docs/develop/)
-To build the documentation, go to the build directory and run
+To build the documentation run
```
make doc
-INFO - Cleaning site directory
-INFO - Building documentation to directory: /home/vagrant/build/site-html
```
-This runs `mkdocs build` plus extra transformation of some files and adds
-symlinks (see `CMakeLists.txt` for the exact steps).
-Now you can start webserver for local testing
+For local testing, you can start webserver:
```
build> make serve-doc
to your host:
```
-build> PYTHONPATH=$SRCDIR mkdocs serve --dev-addr 0.0.0.0:8088
+build> mkdocs serve --dev-addr 0.0.0.0:8088
[server:296] Serving on http://0.0.0.0:8088
[handlers:62] Start watching changes
```
### Sanitizer configuration
-::: nominatim.tokenizer.sanitizers.config.SanitizerConfig
+::: nominatim_db.tokenizer.sanitizers.config.SanitizerConfig
options:
heading_level: 6
#### PlaceInfo - information about the place
-::: nominatim.data.place_info.PlaceInfo
+::: nominatim_db.data.place_info.PlaceInfo
options:
heading_level: 6
#### PlaceName - extended naming information
-::: nominatim.data.place_name.PlaceName
+::: nominatim_db.data.place_name.PlaceName
options:
heading_level: 6
## Custom token analysis module
-::: nominatim.tokenizer.token_analysis.base.AnalysisModule
+::: nominatim_db.tokenizer.token_analysis.base.AnalysisModule
options:
heading_level: 6
-::: nominatim.tokenizer.token_analysis.base.Analyzer
+::: nominatim_db.tokenizer.token_analysis.base.Analyzer
options:
heading_level: 6
The tests can be configured with a set of environment variables (`behave -D key=val`):
- * `BUILDDIR` - build directory of Nominatim installation to test
* `TEMPLATE_DB` - name of template database used as a skeleton for
the test databases (db tests)
* `TEST_DB` - name of test database (db tests)
* `DB_USER` - (optional) username of database login
* `DB_PASS` - (optional) password for database login
* `SERVER_MODULE_PATH` - (optional) path on the Postgres server to Nominatim
- module shared library file
+ module shared library file (only needed for legacy tokenizer)
* `REMOVE_TEMPLATE` - if true, the template and API database will not be reused
during the next run. Reusing the base templates speeds
up tests considerably but might lead to outdated errors
API tests should only be testing the functionality of the website PHP code.
Most tests should be formulated as BDD DB creation tests (see below) instead.
-#### Code Coverage (PHP engine only)
-
-The API tests also support code coverage tests. You need to install
-[PHP_CodeCoverage](https://github.com/sebastianbergmann/php-code-coverage).
-On Debian/Ubuntu run:
-
- apt-get install php-codecoverage php-xdebug
-
-Then run the API tests as follows:
-
- behave api -DPHPCOV=<coverage output dir>
-
-The output directory must be an absolute path. To generate reports, you can use
-the [phpcov](https://github.com/sebastianbergmann/phpcov) tool:
-
- phpcov merge --html=<report output dir> <coverage output dir>
-
### DB Creation Tests (`test/bdd/db`)
These tests check the import and update of the Nominatim database. They do not
### Python Tokenizer Class
-All tokenizers must inherit from `nominatim.tokenizer.base.AbstractTokenizer`
+All tokenizers must inherit from `nominatim_db.tokenizer.base.AbstractTokenizer`
and implement the abstract functions defined there.
-::: nominatim.tokenizer.base.AbstractTokenizer
+::: nominatim_db.tokenizer.base.AbstractTokenizer
options:
heading_level: 6
### Python Analyzer Class
-::: nominatim.tokenizer.base.AbstractAnalyzer
+::: nominatim_db.tokenizer.base.AbstractAnalyzer
options:
heading_level: 6
## `Configuration` class
-::: nominatim.config.Configuration
+::: nominatim_api.Configuration
options:
members:
- get_bool
The library interface is currently in an experimental stage. There might
be some smaller adjustments to the public interface until the next version.
- The library also misses a proper installation routine, so some manipulation
- of the PYTHONPATH is required. At the moment, use is only recommended for
- developers with some experience in Python.
-
## Installation
To use the Nominatim library, you need access to a local Nominatim database.
Follow the [installation](../admin/Installation.md) and
[import](../admin/Import.md) instructions to set up your database.
-It is not yet possible to install it in the usual way via pip or inside a
-virtualenv. To get access to the library you need to set an appropriate
-`PYTHONPATH`. With the default installation, the python library can be found
-under `/usr/local/share/nominatim/lib-python`. If you have installed
-Nominatim under a different prefix, adapt the `/usr/local/` part accordingly.
-You can also point the `PYTHONPATH` to the Nominatim source code.
+The Nominatim frontend library is contained in the Python package `nominatim-api`.
+To install the package from the source tree directly, run:
+
+ pip install packaging/nominatim-api
+
+Usually you would want to run this in a virtual environment.
### A simple search example
from pathlib import Path
import asyncio
- import nominatim.api as napi
+ import nominatim_api as napi
async def search(query):
api = napi.NominatimAPIAsync(Path('.'))
``` python
from pathlib import Path
- import nominatim.api as napi
+ import nominatim_api as napi
api = napi.NominatimAPI(Path('.'))
from pathlib import Path
import asyncio
- import nominatim.api as napi
+ import nominatim_api as napi
config_params = {
'NOMINATIM_DATABASE_DSN': 'pgsql:dbname=belgium'
``` python
from pathlib import Path
- import nominatim.api as napi
+ import nominatim_api as napi
config_params = {
'NOMINATIM_DATABASE_DSN': 'pgsql:dbname=belgium'
from pathlib import Path
import asyncio
- import nominatim.api as napi
+ import nominatim_api as napi
async def search(query):
api = napi.NominatimAPIAsync(Path('.'))
``` python
from pathlib import Path
- import nominatim.api as napi
+ import nominatim_api as napi
api = napi.NominatimAPI(Path('.'))
## Place identification
-The [details](NominatimAPI.md#nominatim.api.core.NominatimAPI.details) and
-[lookup](NominatimAPI.md#nominatim.api.core.NominatimAPI.lookup) functions
+The [details](NominatimAPI.md#nominatim_api.NominatimAPI.details) and
+[lookup](NominatimAPI.md#nominatim_api.NominatimAPI.lookup) functions
require references to places in the database. Below the possible
types for place identification are listed. All types are dataclasses.
### PlaceID
-::: nominatim.api.PlaceID
+::: nominatim_api.PlaceID
options:
heading_level: 6
### OsmID
-::: nominatim.api.OsmID
+::: nominatim_api.OsmID
options:
heading_level: 6
## Geometry types
-::: nominatim.api.GeometryFormat
+::: nominatim_api.GeometryFormat
options:
heading_level: 6
members_order: source
### Point
-::: nominatim.api.Point
+::: nominatim_api.Point
options:
heading_level: 6
show_signature_annotations: True
### Bbox
-::: nominatim.api.Bbox
+::: nominatim_api.Bbox
options:
heading_level: 6
show_signature_annotations: True
geographic extent.
-::: nominatim.api.DataLayer
+::: nominatim_api.DataLayer
options:
heading_level: 6
members_order: source
-
-
import asyncio
from pathlib import Path
import sqlalchemy as sa
-from nominatim.api import NominatimAPIAsync
+from nominatim_api import NominatimAPIAsync
async def print_table_size():
api = NominatimAPIAsync(Path('.'))
## SearchConnection class
-::: nominatim.api.SearchConnection
+::: nominatim_api.SearchConnection
options:
members:
- scalar
### NominatimAPI
-::: nominatim.api.NominatimAPI
+::: nominatim_api.NominatimAPI
options:
members:
- __init__
### NominatimAPIAsync
-::: nominatim.api.NominatimAPIAsync
+::: nominatim_api.NominatimAPIAsync
options:
members:
- __init__
Nominatim takes the result data from multiple sources. The `source_table` field
in the result describes, from which source the result was retrieved.
-::: nominatim.api.SourceTable
+::: nominatim_api.SourceTable
options:
heading_level: 6
members_order: source
for the house number or the country code. This makes processing and creating
a full address easier.
-::: nominatim.api.AddressLine
+::: nominatim_api.AddressLine
options:
heading_level: 6
members_order: source
terms are split into terms for the name of the place and search terms for
its address.
-::: nominatim.api.WordInfo
+::: nominatim_api.WordInfo
options:
heading_level: 6
### Locale
-::: nominatim.api.Locales
+::: nominatim_api.Locales
options:
heading_level: 6
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+from pathlib import Path
+
+import mkdocs_gen_files
+
+VAGRANT_PATH = Path(__file__, '..', '..', 'vagrant').resolve()
+
+for infile in VAGRANT_PATH.glob('Install-on-*.sh'):
+ outfile = f"admin/{infile.stem}.md"
+ title = infile.stem.replace('-', ' ')
+
+ with mkdocs_gen_files.open(outfile, "w") as outfd, infile.open() as infd:
+ print("#", title, file=outfd)
+ has_empty = False
+ for line in infd:
+ line = line.rstrip()
+ docpos = line.find('#DOCS:')
+ if docpos >= 0:
+ line = line[docpos + 6:]
+ elif line == '#' or line.startswith('#!'):
+ line = ''
+ elif line.startswith('# '):
+ line = line[2:]
+ if line or not has_empty:
+ print(line, file=outfd)
+ has_empty = not bool(line)
+
+ mkdocs_gen_files.set_edit_path(outfile, "docs/mk_install_instructions.py")
-- Index is needed during import but can be dropped as soon as a full
-- geometry index is in place. The partial index is almost as big as the full
-- index.
+---
DROP INDEX IF EXISTS idx_placex_geometry_lower_rank_ways;
---
CREATE INDEX IF NOT EXISTS idx_placex_geometry_reverse_lookupPolygon
---
DROP INDEX IF EXISTS idx_placex_geometry_address_area_candidates;
DROP INDEX IF EXISTS idx_placex_geometry_buildings;
- DROP INDEX IF EXISTS idx_placex_geometry_lower_rank_ways;
DROP INDEX IF EXISTS idx_placex_wikidata;
DROP INDEX IF EXISTS idx_placex_rank_address_sector;
DROP INDEX IF EXISTS idx_placex_rank_boundaries_sector;
+++ /dev/null
-# Creates and installs manual page
-
-configure_file(${CMAKE_CURRENT_SOURCE_DIR}/create-manpage.tmpl create_manpage.py)
-
-find_program(ARGPARSEMANPAGE argparse-manpage)
-
-ADD_CUSTOM_TARGET(manpage
- COMMAND ${ARGPARSEMANPAGE} --pyfile ${CMAKE_CURRENT_BINARY_DIR}/create_manpage.py
- --function get_parser --project-name Nominatim
- --url https://nominatim.org > ${CMAKE_CURRENT_SOURCE_DIR}/nominatim.1
- --author 'the Nominatim developer community'
- --author-email info@nominatim.org
-)
-
-install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/nominatim.1 DESTINATION share/man/man1 )
--- /dev/null
+import sys
+import os
+from pathlib import Path
+
+sys.path.append(str(Path(__file__, '..', '..', 'src').resolve()))
+
+from nominatim_db.cli import get_set_parser
+
+def get_parser():
+ parser = get_set_parser()
+
+ return parser.parser
+++ /dev/null
-#!/usr/bin/env python3
-import sys
-import os
-
-sys.path.append('@PROJECT_SOURCE_DIR@')
-
-from nominatim.cli import get_set_parser
-
-def get_parser():
- parser = get_set_parser()
-
- return parser.parser
nominatim
.SH SYNOPSIS
.B nominatim
-[-h] {import,freeze,replication,special-phrases,add-data,index,refresh,admin,export,serve,search,reverse,lookup,details,status} ...
+[-h] [--version] {import,freeze,replication,special-phrases,add-data,index,refresh,admin,export,convert,serve,search,reverse,lookup,details,status} ...
.SH DESCRIPTION
Command\-line tools for importing, updating, administrating and
.br
.SH OPTIONS
+.TP
+\fB\-\-version\fR
+Print Nominatim version and exit
.SS
\fBSub-commands\fR
Analyse and maintain the database.
.TP
\fBnominatim\fR \fI\,export\/\fR
- Export addresses as CSV file from the database.
+ Export places as CSV file from the database.
+.TP
+\fBnominatim\fR \fI\,convert\/\fR
+ Convert an existing database into a different format. (EXPERIMENTAL)
.TP
\fBnominatim\fR \fI\,serve\/\fR
Start a simple web server for serving the API.
Execute API details query.
.TP
\fBnominatim\fR \fI\,status\/\fR
- Execute API status query.
+
.SH OPTIONS 'nominatim import'
usage: nominatim import [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
- (--osm-file FILE | --continue {load-data,indexing,db-postprocess})
+ [--osm-file FILE]
+ [--continue {import-from-file,load-data,indexing,db-postprocess}]
[--osm2pgsql-cache SIZE] [--reverse-only]
- [--no-partitions] [--no-updates] [--ignore-errors]
- [--index-noanalyse]
+ [--no-partitions] [--no-updates] [--offline]
+ [--ignore-errors] [--index-noanalyse]
+ [--prepare-database]
Create a new Nominatim database from an OSM file.
.br
OSM file to be imported (repeat for importing multiple files)
.TP
-\fB\-\-continue\fR {load\-data,indexing,db\-postprocess}
+\fB\-\-continue\fR {import\-from\-file,load\-data,indexing,db\-postprocess}
Continue an import that was interrupted
.TP
\fB\-\-no\-updates\fR
Do not keep tables that are only needed for updating the database later
+.TP
+\fB\-\-offline\fR
+Do not attempt to load any additional data from the internet
+
.TP
\fB\-\-ignore\-errors\fR
Continue import even when errors in SQL are present
\fB\-\-index\-noanalyse\fR
Do not perform analyse operations during index (expert only)
+.TP
+\fB\-\-prepare\-database\fR
+Create the database but do not import any data
+
.SH OPTIONS 'nominatim freeze'
usage: nominatim freeze [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
.SH OPTIONS 'nominatim replication'
usage: nominatim replication [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
[--init] [--no-update-functions]
- [--check-for-updates] [--once] [--no-index]
- [--osm2pgsql-cache SIZE]
+ [--check-for-updates] [--once] [--catch-up]
+ [--no-index] [--osm2pgsql-cache SIZE]
[--socket-timeout SOCKET_TIMEOUT]
Update the database using an online replication service.
.TP
\fB\-\-no\-update\-functions\fR
-Do not update the trigger function to support differential updates.
+Do not update the trigger function to support differential updates (EXPERT)
.TP
\fB\-\-check\-for\-updates\fR
\fB\-\-once\fR
Download and apply updates only once. When not set, updates are continuously applied
+.TP
+\fB\-\-catch\-up\fR
+Download and apply updates until no new data is available on the server
+
.TP
\fB\-\-no\-index\fR
Do not index the new data. Only usable together with \-\-once
.br
'test/testdb/full_en_phrases_test.csv'.
.br
+
+.br
+ The import can be further configured to ignore specific key/value pairs.
+.br
+ This is particularly useful when importing phrases from the wiki. The
+.br
+ default configuration excludes some very common tags like building=yes.
+.br
+ The configuration can be customized by putting a file `phrase\-settings.json`
+.br
+ with custom rules into the project directory or by using the `\-\-config`
+.br
+ option to point to another configuration file.
+.br
.br
data. See the online documentation at
.br
- https://nominatim.org/release\-docs/latest/admin/Import/#installing\-tiger\-housenumber\-data\-for\-the\-us
+ https://nominatim.org/release\-docs/latest/customize/Tiger/
.br
for more information.
.br
.SH OPTIONS 'nominatim refresh'
usage: nominatim refresh [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
- [--postcodes] [--word-counts] [--address-levels]
- [--functions] [--wiki-data] [--importance]
- [--website] [--no-diff-updates]
- [--enable-debug-statements]
+ [--postcodes] [--word-tokens] [--word-counts]
+ [--address-levels] [--functions] [--wiki-data]
+ [--secondary-importance] [--importance] [--website]
+ [--data-object OBJECT] [--data-area OBJECT]
+ [--no-diff-updates] [--enable-debug-statements]
Recompute auxiliary data used by the indexing process.
.br
\fB\-\-postcodes\fR
Update postcode centroid table
+.TP
+\fB\-\-word\-tokens\fR
+Clean up search terms
+
.TP
\fB\-\-word\-counts\fR
Compute frequency of full\-word search terms
\fB\-\-wiki\-data\fR
Update Wikipedia/data importance numbers
+.TP
+\fB\-\-secondary\-importance\fR
+Update secondary importance raster data
+
.TP
\fB\-\-importance\fR
Recompute place importances (expensive!)
\fB\-\-website\fR
Refresh the directory that serves the scripts for the web API
+.TP
+\fB\-\-data\-object\fR OBJECT
+Mark the given OSM object as requiring an update (format: [NWR]<id>)
+
+.TP
+\fB\-\-data\-area\fR OBJECT
+Mark the area around the given OSM object as requiring an update (format: [NWR]<id>)
+
.TP
\fB\-\-no\-diff\-updates\fR
Do not enable code for propagating updates
.SH OPTIONS 'nominatim admin'
usage: nominatim admin [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
- (--warm | --check-database | --migrate | --analyse-indexing)
+ (--warm | --check-database | --migrate | --analyse-indexing | --collect-os-info | --clean-deleted AGE)
[--search-only] [--reverse-only]
[--osm-id OSM_ID | --place-id PLACE_ID]
\fB\-\-analyse\-indexing\fR
Print performance analysis of the indexing process
+.TP
+\fB\-\-collect\-os\-info\fR
+Generate a report about the host system information
+
+.TP
+\fB\-\-clean\-deleted\fR AGE
+Clean up deleted relations
+
.TP
\fB\-\-search\-only\fR
Only pre\-warm tables for search queries
.SH OPTIONS 'nominatim export'
usage: nominatim export [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
- [--output-type {continent,country,state,county,city,suburb,street,path}]
- [--output-format OUTPUT_FORMAT]
- [--output-all-postcodes] [--language LANGUAGE]
+ [--output-type {country,state,county,city,suburb,street,path}]
+ [--output-format OUTPUT_FORMAT] [--language LANGUAGE]
[--restrict-to-country COUNTRY_CODE]
[--restrict-to-osm-node ID] [--restrict-to-osm-way ID]
[--restrict-to-osm-relation ID]
- Export addresses as CSV file from the database.
+ Export places as CSV file from the database.
+.br
+
+.br
+
.br
Number of parallel threads to use
.TP
-\fB\-\-output\-type\fR {continent,country,state,county,city,suburb,street,path}
+\fB\-\-output\-type\fR {country,state,county,city,suburb,street,path}
Type of places to output (default: street)
.TP
\fB\-\-output\-format\fR \fI\,OUTPUT_FORMAT\/\fR
-Semicolon\-separated list of address types (see \-\-output\-type). Multiple ranks can be merged into one column by simply using a comma\-separated list.
-
-.TP
-\fB\-\-output\-all\-postcodes\fR
-List all postcodes for address instead of just the most likely one
+Semicolon\-separated list of address types (see \-\-output\-type). Additionally accepts:placeid,postcode
.TP
\fB\-\-language\fR \fI\,LANGUAGE\/\fR
\fB\-\-restrict\-to\-osm\-relation\fR ID
Export only children of this OSM relation
+.SH OPTIONS 'nominatim convert'
+usage: nominatim convert [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
+ [--format {sqlite}] --output OUTPUT [--with-reverse]
+ [--with-search] [--with-details]
+
+ Convert an existing database into a different format. (EXPERIMENTAL)
+.br
+
+.br
+ Dump a read\-only version of the database in a different format.
+.br
+ At the moment only a SQLite database suitable for reverse lookup
+.br
+ can be created.
+.br
+
+
+
+.TP
+\fB\-\-format\fR {sqlite}
+Format of the output database (must be sqlite currently)
+
+.TP
+\fB\-\-output\fR \fI\,OUTPUT\/\fR, \fB\-o\fR \fI\,OUTPUT\/\fR
+File to write the database to.
+
+.TP
+\fB\-q\fR, \fB\-\-quiet\fR
+Print only error messages
+
+.TP
+\fB\-v\fR, \fB\-\-verbose\fR
+Increase verboseness of output
+
+.TP
+\fB\-\-project\-dir\fR DIR
+Base directory of the Nominatim installation (default:.)
+
+.TP
+\fB\-j\fR NUM, \fB\-\-threads\fR NUM
+Number of parallel threads to use
+
+.TP
+\fB\-\-with\-reverse\fR, \fB\-\-without\-reverse\fR
+Enable/disable support for reverse and lookup API (default: enabled)
+
+.TP
+\fB\-\-with\-search\fR, \fB\-\-without\-search\fR
+Enable/disable support for search API (default: disabled)
+
+.TP
+\fB\-\-with\-details\fR, \fB\-\-without\-details\fR
+Enable/disable support for details API (default: enabled)
+
.SH OPTIONS 'nominatim serve'
usage: nominatim serve [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
- [--server SERVER]
+ [--server SERVER] [--engine {php,falcon,starlette}]
Start a simple web server for serving the API.
.br
.br
- This command starts the built\-in PHP webserver to serve the website
+ This command starts a built\-in webserver to serve the website
.br
from the current project directory. This webserver is only suitable
.br
for testing and development. Do not use it in production setups!
.br
+.br
+ There are different webservers available. The default 'php' engine
+.br
+ runs the classic PHP frontend. The other engines are Python servers
+.br
+ which run the new Python frontend code. This is highly experimental
+.br
+ at the moment and may not include the full API.
+.br
+
.br
By the default, the webserver can be accessed at: http://127.0.0.1:8088
.br
\fB\-\-server\fR \fI\,SERVER\/\fR
The address the server will listen to.
+.TP
+\fB\-\-engine\fR {php,falcon,starlette}
+Webserver framework to run. (default: falcon)
+
.SH OPTIONS 'nominatim search'
usage: nominatim search [-h] [-q] [-v] [--project-dir DIR] [-j NUM]
- [--query QUERY] [--street STREET] [--city CITY]
- [--county COUNTY] [--state STATE] [--country COUNTRY]
- [--postalcode POSTALCODE]
- [--format {xml,json,jsonv2,geojson,geocodejson}]
+ [--query QUERY] [--amenity AMENITY] [--street STREET]
+ [--city CITY] [--county COUNTY] [--state STATE]
+ [--country COUNTRY] [--postalcode POSTALCODE]
+ [--format {xml,geojson,geocodejson,json,jsonv2,debug}]
[--addressdetails] [--extratags] [--namedetails]
[--lang LANGS]
[--polygon-output {geojson,kml,svg,text}]
\fB\-\-query\fR \fI\,QUERY\/\fR
Free\-form query string
+.TP
+\fB\-\-amenity\fR \fI\,AMENITY\/\fR
+Structured query: name and/or type of POI
+
.TP
\fB\-\-street\fR \fI\,STREET\/\fR
Structured query: housenumber and street
Structured query: postcode
.TP
-\fB\-\-format\fR {xml,json,jsonv2,geojson,geocodejson}
+\fB\-\-format\fR {xml,geojson,geocodejson,json,jsonv2,debug}
Format of result
.TP
.SH OPTIONS 'nominatim reverse'
usage: nominatim reverse [-h] [-q] [-v] [--project-dir DIR] [-j NUM] --lat LAT
- --lon LON [--zoom ZOOM]
- [--format {xml,json,jsonv2,geojson,geocodejson}]
+ --lon LON [--zoom ZOOM] [--layer LAYER]
+ [--format {xml,geojson,geocodejson,json,jsonv2,debug}]
[--addressdetails] [--extratags] [--namedetails]
[--lang LANGS]
[--polygon-output {geojson,kml,svg,text}]
Level of detail required for the address
.TP
-\fB\-\-format\fR {xml,json,jsonv2,geojson,geocodejson}
+\fB\-\-layer\fR LAYER
+OSM id to lookup in format <NRW><id> (may be repeated)
+
+.TP
+\fB\-\-format\fR {xml,geojson,geocodejson,json,jsonv2,debug}
Format of result
.TP
.SH OPTIONS 'nominatim lookup'
usage: nominatim lookup [-h] [-q] [-v] [--project-dir DIR] [-j NUM] --id OSMID
- [--format {xml,json,jsonv2,geojson,geocodejson}]
+ [--format {xml,geojson,geocodejson,json,jsonv2,debug}]
[--addressdetails] [--extratags] [--namedetails]
[--lang LANGS]
[--polygon-output {geojson,kml,svg,text}]
OSM id to lookup in format <NRW><id> (may be repeated)
.TP
-\fB\-\-format\fR {xml,json,jsonv2,geojson,geocodejson}
+\fB\-\-format\fR {xml,geojson,geocodejson,json,jsonv2,debug}
Format of result
.TP
features:
- navigation.tabs
copyright: Copyright © Nominatim developer community
-docs_dir: ${CMAKE_CURRENT_BINARY_DIR}
+docs_dir: docs
site_url: https://nominatim.org
repo_url: https://github.com/openstreetmap/Nominatim
nav:
- 'Maintenance' : 'admin/Maintenance.md'
- 'Migration from older Versions' : 'admin/Migration.md'
- 'Troubleshooting' : 'admin/Faq.md'
+ - 'Installation on Ubuntu 22' : 'admin/Install-on-Ubuntu-22.md'
+ - 'Installation on Ubuntu 24' : 'admin/Install-on-Ubuntu-24.md'
- 'Customization Guide':
- 'Overview': 'customize/Overview.md'
- 'Import Styles': 'customize/Import-Styles.md'
- 'Setup for Development' : 'develop/Development-Environment.md'
- 'Testing' : 'develop/Testing.md'
- 'External Data Sources': 'develop/data-sources.md'
- - 'Appendix':
- - 'Installation on Ubuntu 20' : 'appendix/Install-on-Ubuntu-20.md'
- - 'Installation on Ubuntu 22' : 'appendix/Install-on-Ubuntu-22.md'
markdown_extensions:
- codehilite
- admonition
- toc:
permalink:
extra_css: [extra.css, styles.css]
+exclude_docs: |
+ mk_install_instructions.py
+site_dir: site-html
plugins:
- search
- mkdocstrings:
handlers:
python:
- paths: ["${PROJECT_SOURCE_DIR}"]
+ paths: ["src"]
options:
show_source: False
show_bases: False
+ - gen-files:
+ scripts:
+ - docs/mk_install_instructions.py
--- /dev/null
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Helper script for development to run nominatim from the source directory.
+"""
+from pathlib import Path
+import sys
+
+sys.path.insert(1, str((Path(__file__) / '..' / 'src').resolve()))
+
+from nominatim_db import cli
+
+exit(cli.nominatim(module_dir=None, osm2pgsql_path=None))
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2023 by the Nominatim developer community.
-# For a full list of authors see the git log.
-"""
-Subcommand definitions for the command-line tool.
-"""
-# mypy and pylint disagree about the style of explicit exports,
-# see https://github.com/PyCQA/pylint/issues/6006.
-# pylint: disable=useless-import-alias
-
-from nominatim.clicmd.setup import SetupAll as SetupAll
-from nominatim.clicmd.replication import UpdateReplication as UpdateReplication
-from nominatim.clicmd.api import (APISearch as APISearch,
- APIReverse as APIReverse,
- APILookup as APILookup,
- APIDetails as APIDetails,
- APIStatus as APIStatus)
-from nominatim.clicmd.index import UpdateIndex as UpdateIndex
-from nominatim.clicmd.refresh import UpdateRefresh as UpdateRefresh
-from nominatim.clicmd.add_data import UpdateAddData as UpdateAddData
-from nominatim.clicmd.admin import AdminFuncs as AdminFuncs
-from nominatim.clicmd.freeze import SetupFreeze as SetupFreeze
-from nominatim.clicmd.special_phrases import ImportSpecialPhrases as ImportSpecialPhrases
-from nominatim.clicmd.export import QueryExport as QueryExport
-from nominatim.clicmd.convert import ConvertDB as ConvertDB
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2022 by the Nominatim developer community.
-# For a full list of authors see the git log.
-""" Non-blocking database connections.
-"""
-from typing import Callable, Any, Optional, Iterator, Sequence
-import logging
-import select
-import time
-
-import psycopg2
-from psycopg2.extras import wait_select
-
-# psycopg2 emits different exceptions pre and post 2.8. Detect if the new error
-# module is available and adapt the error handling accordingly.
-try:
- import psycopg2.errors # pylint: disable=no-name-in-module,import-error
- __has_psycopg2_errors__ = True
-except ImportError:
- __has_psycopg2_errors__ = False
-
-from nominatim.typing import T_cursor, Query
-
-LOG = logging.getLogger()
-
-class DeadlockHandler:
- """ Context manager that catches deadlock exceptions and calls
- the given handler function. All other exceptions are passed on
- normally.
- """
-
- def __init__(self, handler: Callable[[], None], ignore_sql_errors: bool = False) -> None:
- self.handler = handler
- self.ignore_sql_errors = ignore_sql_errors
-
- def __enter__(self) -> 'DeadlockHandler':
- return self
-
- def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> bool:
- if __has_psycopg2_errors__:
- if exc_type == psycopg2.errors.DeadlockDetected: # pylint: disable=E1101
- self.handler()
- return True
- elif exc_type == psycopg2.extensions.TransactionRollbackError \
- and exc_value.pgcode == '40P01':
- self.handler()
- return True
-
- if self.ignore_sql_errors and isinstance(exc_value, psycopg2.Error):
- LOG.info("SQL error ignored: %s", exc_value)
- return True
-
- return False
-
-
-class DBConnection:
- """ A single non-blocking database connection.
- """
-
- def __init__(self, dsn: str,
- cursor_factory: Optional[Callable[..., T_cursor]] = None,
- ignore_sql_errors: bool = False) -> None:
- self.dsn = dsn
-
- self.current_query: Optional[Query] = None
- self.current_params: Optional[Sequence[Any]] = None
- self.ignore_sql_errors = ignore_sql_errors
-
- self.conn: Optional['psycopg2._psycopg.connection'] = None
- self.cursor: Optional['psycopg2._psycopg.cursor'] = None
- self.connect(cursor_factory=cursor_factory)
-
- def close(self) -> None:
- """ Close all open connections. Does not wait for pending requests.
- """
- if self.conn is not None:
- if self.cursor is not None:
- self.cursor.close()
- self.cursor = None
- self.conn.close()
-
- self.conn = None
-
- def connect(self, cursor_factory: Optional[Callable[..., T_cursor]] = None) -> None:
- """ (Re)connect to the database. Creates an asynchronous connection
- with JIT and parallel processing disabled. If a connection was
- already open, it is closed and a new connection established.
- The caller must ensure that no query is pending before reconnecting.
- """
- self.close()
-
- # Use a dict to hand in the parameters because async is a reserved
- # word in Python3.
- self.conn = psycopg2.connect(**{'dsn': self.dsn, 'async': True}) # type: ignore
- assert self.conn
- self.wait()
-
- if cursor_factory is not None:
- self.cursor = self.conn.cursor(cursor_factory=cursor_factory)
- else:
- self.cursor = self.conn.cursor()
- # Disable JIT and parallel workers as they are known to cause problems.
- # Update pg_settings instead of using SET because it does not yield
- # errors on older versions of Postgres where the settings are not
- # implemented.
- self.perform(
- """ UPDATE pg_settings SET setting = -1 WHERE name = 'jit_above_cost';
- UPDATE pg_settings SET setting = 0
- WHERE name = 'max_parallel_workers_per_gather';""")
- self.wait()
-
- def _deadlock_handler(self) -> None:
- LOG.info("Deadlock detected (params = %s), retry.", str(self.current_params))
- assert self.cursor is not None
- assert self.current_query is not None
- assert self.current_params is not None
-
- self.cursor.execute(self.current_query, self.current_params)
-
- def wait(self) -> None:
- """ Block until any pending operation is done.
- """
- while True:
- with DeadlockHandler(self._deadlock_handler, self.ignore_sql_errors):
- wait_select(self.conn)
- self.current_query = None
- return
-
- def perform(self, sql: Query, args: Optional[Sequence[Any]] = None) -> None:
- """ Send SQL query to the server. Returns immediately without
- blocking.
- """
- assert self.cursor is not None
- self.current_query = sql
- self.current_params = args
- self.cursor.execute(sql, args)
-
- def fileno(self) -> int:
- """ File descriptor to wait for. (Makes this class select()able.)
- """
- assert self.conn is not None
- return self.conn.fileno()
-
- def is_done(self) -> bool:
- """ Check if the connection is available for a new query.
-
- Also checks if the previous query has run into a deadlock.
- If so, then the previous query is repeated.
- """
- assert self.conn is not None
-
- if self.current_query is None:
- return True
-
- with DeadlockHandler(self._deadlock_handler, self.ignore_sql_errors):
- if self.conn.poll() == psycopg2.extensions.POLL_OK:
- self.current_query = None
- return True
-
- return False
-
-
-class WorkerPool:
- """ A pool of asynchronous database connections.
-
- The pool may be used as a context manager.
- """
- REOPEN_CONNECTIONS_AFTER = 100000
-
- def __init__(self, dsn: str, pool_size: int, ignore_sql_errors: bool = False) -> None:
- self.threads = [DBConnection(dsn, ignore_sql_errors=ignore_sql_errors)
- for _ in range(pool_size)]
- self.free_workers = self._yield_free_worker()
- self.wait_time = 0.0
-
-
- def finish_all(self) -> None:
- """ Wait for all connection to finish.
- """
- for thread in self.threads:
- while not thread.is_done():
- thread.wait()
-
- self.free_workers = self._yield_free_worker()
-
- def close(self) -> None:
- """ Close all connections and clear the pool.
- """
- for thread in self.threads:
- thread.close()
- self.threads = []
- self.free_workers = iter([])
-
-
- def next_free_worker(self) -> DBConnection:
- """ Get the next free connection.
- """
- return next(self.free_workers)
-
-
- def _yield_free_worker(self) -> Iterator[DBConnection]:
- ready = self.threads
- command_stat = 0
- while True:
- for thread in ready:
- if thread.is_done():
- command_stat += 1
- yield thread
-
- if command_stat > self.REOPEN_CONNECTIONS_AFTER:
- self._reconnect_threads()
- ready = self.threads
- command_stat = 0
- else:
- tstart = time.time()
- _, ready, _ = select.select([], self.threads, [])
- self.wait_time += time.time() - tstart
-
-
- def _reconnect_threads(self) -> None:
- for thread in self.threads:
- while not thread.is_done():
- thread.wait()
- thread.connect()
-
-
- def __enter__(self) -> 'WorkerPool':
- return self
-
-
- def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
- self.finish_all()
- self.close()
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2022 by the Nominatim developer community.
-# For a full list of authors see the git log.
-"""
-Specialised connection and cursor functions.
-"""
-from typing import Optional, Any, Callable, ContextManager, Dict, cast, overload, Tuple, Iterable
-import contextlib
-import logging
-import os
-
-import psycopg2
-import psycopg2.extensions
-import psycopg2.extras
-from psycopg2 import sql as pysql
-
-from nominatim.typing import SysEnv, Query, T_cursor
-from nominatim.errors import UsageError
-
-LOG = logging.getLogger()
-
-class Cursor(psycopg2.extras.DictCursor):
- """ A cursor returning dict-like objects and providing specialised
- execution functions.
- """
- # pylint: disable=arguments-renamed,arguments-differ
- def execute(self, query: Query, args: Any = None) -> None:
- """ Query execution that logs the SQL query when debugging is enabled.
- """
- if LOG.isEnabledFor(logging.DEBUG):
- LOG.debug(self.mogrify(query, args).decode('utf-8'))
-
- super().execute(query, args)
-
-
- def execute_values(self, sql: Query, argslist: Iterable[Tuple[Any, ...]],
- template: Optional[Query] = None) -> None:
- """ Wrapper for the psycopg2 convenience function to execute
- SQL for a list of values.
- """
- LOG.debug("SQL execute_values(%s, %s)", sql, argslist)
-
- psycopg2.extras.execute_values(self, sql, argslist, template=template)
-
-
- def scalar(self, sql: Query, args: Any = None) -> Any:
- """ Execute query that returns a single value. The value is returned.
- If the query yields more than one row, a ValueError is raised.
- """
- self.execute(sql, args)
-
- if self.rowcount != 1:
- raise RuntimeError("Query did not return a single row.")
-
- result = self.fetchone()
- assert result is not None
-
- return result[0]
-
-
- def drop_table(self, name: str, if_exists: bool = True, cascade: bool = False) -> None:
- """ Drop the table with the given name.
- Set `if_exists` to False if a non-existent table should raise
- an exception instead of just being ignored. If 'cascade' is set
- to True then all dependent tables are deleted as well.
- """
- sql = 'DROP TABLE '
- if if_exists:
- sql += 'IF EXISTS '
- sql += '{}'
- if cascade:
- sql += ' CASCADE'
-
- self.execute(pysql.SQL(sql).format(pysql.Identifier(name)))
-
-
-class Connection(psycopg2.extensions.connection):
- """ A connection that provides the specialised cursor by default and
- adds convenience functions for administrating the database.
- """
- @overload # type: ignore[override]
- def cursor(self) -> Cursor:
- ...
-
- @overload
- def cursor(self, name: str) -> Cursor:
- ...
-
- @overload
- def cursor(self, cursor_factory: Callable[..., T_cursor]) -> T_cursor:
- ...
-
- def cursor(self, cursor_factory = Cursor, **kwargs): # type: ignore
- """ Return a new cursor. By default the specialised cursor is returned.
- """
- return super().cursor(cursor_factory=cursor_factory, **kwargs)
-
-
- def table_exists(self, table: str) -> bool:
- """ Check that a table with the given name exists in the database.
- """
- with self.cursor() as cur:
- num = cur.scalar("""SELECT count(*) FROM pg_tables
- WHERE tablename = %s and schemaname = 'public'""", (table, ))
- return num == 1 if isinstance(num, int) else False
-
-
- def table_has_column(self, table: str, column: str) -> bool:
- """ Check if the table 'table' exists and has a column with name 'column'.
- """
- with self.cursor() as cur:
- has_column = cur.scalar("""SELECT count(*) FROM information_schema.columns
- WHERE table_name = %s
- and column_name = %s""",
- (table, column))
- return has_column > 0 if isinstance(has_column, int) else False
-
-
- def index_exists(self, index: str, table: Optional[str] = None) -> bool:
- """ Check that an index with the given name exists in the database.
- If table is not None then the index must relate to the given
- table.
- """
- with self.cursor() as cur:
- cur.execute("""SELECT tablename FROM pg_indexes
- WHERE indexname = %s and schemaname = 'public'""", (index, ))
- if cur.rowcount == 0:
- return False
-
- if table is not None:
- row = cur.fetchone()
- if row is None or not isinstance(row[0], str):
- return False
- return row[0] == table
-
- return True
-
-
- def drop_table(self, name: str, if_exists: bool = True, cascade: bool = False) -> None:
- """ Drop the table with the given name.
- Set `if_exists` to False if a non-existent table should raise
- an exception instead of just being ignored.
- """
- with self.cursor() as cur:
- cur.drop_table(name, if_exists, cascade)
- self.commit()
-
-
- def server_version_tuple(self) -> Tuple[int, int]:
- """ Return the server version as a tuple of (major, minor).
- Converts correctly for pre-10 and post-10 PostgreSQL versions.
- """
- version = self.server_version
- if version < 100000:
- return (int(version / 10000), int((version % 10000) / 100))
-
- return (int(version / 10000), version % 10000)
-
-
- def postgis_version_tuple(self) -> Tuple[int, int]:
- """ Return the postgis version installed in the database as a
- tuple of (major, minor). Assumes that the PostGIS extension
- has been installed already.
- """
- with self.cursor() as cur:
- version = cur.scalar('SELECT postgis_lib_version()')
-
- version_parts = version.split('.')
- if len(version_parts) < 2:
- raise UsageError(f"Error fetching Postgis version. Bad format: {version}")
-
- return (int(version_parts[0]), int(version_parts[1]))
-
-
- def extension_loaded(self, extension_name: str) -> bool:
- """ Return True if the hstore extension is loaded in the database.
- """
- with self.cursor() as cur:
- cur.execute('SELECT extname FROM pg_extension WHERE extname = %s', (extension_name, ))
- return cur.rowcount > 0
-
-
-class ConnectionContext(ContextManager[Connection]):
- """ Context manager of the connection that also provides direct access
- to the underlying connection.
- """
- connection: Connection
-
-def connect(dsn: str) -> ConnectionContext:
- """ Open a connection to the database using the specialised connection
- factory. The returned object may be used in conjunction with 'with'.
- When used outside a context manager, use the `connection` attribute
- to get the connection.
- """
- try:
- conn = psycopg2.connect(dsn, connection_factory=Connection)
- ctxmgr = cast(ConnectionContext, contextlib.closing(conn))
- ctxmgr.connection = conn
- return ctxmgr
- except psycopg2.OperationalError as err:
- raise UsageError(f"Cannot connect to database: {err}") from err
-
-
-# Translation from PG connection string parameters to PG environment variables.
-# Derived from https://www.postgresql.org/docs/current/libpq-envars.html.
-_PG_CONNECTION_STRINGS = {
- 'host': 'PGHOST',
- 'hostaddr': 'PGHOSTADDR',
- 'port': 'PGPORT',
- 'dbname': 'PGDATABASE',
- 'user': 'PGUSER',
- 'password': 'PGPASSWORD',
- 'passfile': 'PGPASSFILE',
- 'channel_binding': 'PGCHANNELBINDING',
- 'service': 'PGSERVICE',
- 'options': 'PGOPTIONS',
- 'application_name': 'PGAPPNAME',
- 'sslmode': 'PGSSLMODE',
- 'requiressl': 'PGREQUIRESSL',
- 'sslcompression': 'PGSSLCOMPRESSION',
- 'sslcert': 'PGSSLCERT',
- 'sslkey': 'PGSSLKEY',
- 'sslrootcert': 'PGSSLROOTCERT',
- 'sslcrl': 'PGSSLCRL',
- 'requirepeer': 'PGREQUIREPEER',
- 'ssl_min_protocol_version': 'PGSSLMINPROTOCOLVERSION',
- 'ssl_max_protocol_version': 'PGSSLMAXPROTOCOLVERSION',
- 'gssencmode': 'PGGSSENCMODE',
- 'krbsrvname': 'PGKRBSRVNAME',
- 'gsslib': 'PGGSSLIB',
- 'connect_timeout': 'PGCONNECT_TIMEOUT',
- 'target_session_attrs': 'PGTARGETSESSIONATTRS',
-}
-
-
-def get_pg_env(dsn: str,
- base_env: Optional[SysEnv] = None) -> Dict[str, str]:
- """ Return a copy of `base_env` with the environment variables for
- PostgreSQL set up from the given database connection string.
- If `base_env` is None, then the OS environment is used as a base
- environment.
- """
- env = dict(base_env if base_env is not None else os.environ)
-
- for param, value in psycopg2.extensions.parse_dsn(dsn).items():
- if param in _PG_CONNECTION_STRINGS:
- env[_PG_CONNECTION_STRINGS[param]] = value
- else:
- LOG.error("Unknown connection parameter '%s' ignored.", param)
-
- return env
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2022 by the Nominatim developer community.
-# For a full list of authors see the git log.
-"""
-Main work horse for indexing (computing addresses) the database.
-"""
-from typing import Optional, Any, cast
-import logging
-import time
-
-import psycopg2.extras
-
-from nominatim.tokenizer.base import AbstractTokenizer
-from nominatim.indexer.progress import ProgressLogger
-from nominatim.indexer import runners
-from nominatim.db.async_connection import DBConnection, WorkerPool
-from nominatim.db.connection import connect, Connection, Cursor
-from nominatim.typing import DictCursorResults
-
-LOG = logging.getLogger()
-
-
-class PlaceFetcher:
- """ Asynchronous connection that fetches place details for processing.
- """
- def __init__(self, dsn: str, setup_conn: Connection) -> None:
- self.wait_time = 0.0
- self.current_ids: Optional[DictCursorResults] = None
- self.conn: Optional[DBConnection] = DBConnection(dsn,
- cursor_factory=psycopg2.extras.DictCursor)
-
- with setup_conn.cursor() as cur:
- # need to fetch those manually because register_hstore cannot
- # fetch them on an asynchronous connection below.
- hstore_oid = cur.scalar("SELECT 'hstore'::regtype::oid")
- hstore_array_oid = cur.scalar("SELECT 'hstore[]'::regtype::oid")
-
- psycopg2.extras.register_hstore(self.conn.conn, oid=hstore_oid,
- array_oid=hstore_array_oid)
-
- def close(self) -> None:
- """ Close the underlying asynchronous connection.
- """
- if self.conn:
- self.conn.close()
- self.conn = None
-
-
- def fetch_next_batch(self, cur: Cursor, runner: runners.Runner) -> bool:
- """ Send a request for the next batch of places.
- If details for the places are required, they will be fetched
- asynchronously.
-
- Returns true if there is still data available.
- """
- ids = cast(Optional[DictCursorResults], cur.fetchmany(100))
-
- if not ids:
- self.current_ids = None
- return False
-
- assert self.conn is not None
- self.current_ids = runner.get_place_details(self.conn, ids)
-
- return True
-
- def get_batch(self) -> DictCursorResults:
- """ Get the next batch of data, previously requested with
- `fetch_next_batch`.
- """
- assert self.conn is not None
- assert self.conn.cursor is not None
-
- if self.current_ids is not None and not self.current_ids:
- tstart = time.time()
- self.conn.wait()
- self.wait_time += time.time() - tstart
- self.current_ids = cast(Optional[DictCursorResults],
- self.conn.cursor.fetchall())
-
- return self.current_ids if self.current_ids is not None else []
-
- def __enter__(self) -> 'PlaceFetcher':
- return self
-
-
- def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
- assert self.conn is not None
- self.conn.wait()
- self.close()
-
-
-class Indexer:
- """ Main indexing routine.
- """
-
- def __init__(self, dsn: str, tokenizer: AbstractTokenizer, num_threads: int):
- self.dsn = dsn
- self.tokenizer = tokenizer
- self.num_threads = num_threads
-
-
- def has_pending(self) -> bool:
- """ Check if any data still needs indexing.
- This function must only be used after the import has finished.
- Otherwise it will be very expensive.
- """
- with connect(self.dsn) as conn:
- with conn.cursor() as cur:
- cur.execute("SELECT 'a' FROM placex WHERE indexed_status > 0 LIMIT 1")
- return cur.rowcount > 0
-
-
- def index_full(self, analyse: bool = True) -> None:
- """ Index the complete database. This will first index boundaries
- followed by all other objects. When `analyse` is True, then the
- database will be analysed at the appropriate places to
- ensure that database statistics are updated.
- """
- with connect(self.dsn) as conn:
- conn.autocommit = True
-
- def _analyze() -> None:
- if analyse:
- with conn.cursor() as cur:
- cur.execute('ANALYZE')
-
- if self.index_by_rank(0, 4) > 0:
- _analyze()
-
- if self.index_boundaries(0, 30) > 100:
- _analyze()
-
- if self.index_by_rank(5, 25) > 100:
- _analyze()
-
- if self.index_by_rank(26, 30) > 1000:
- _analyze()
-
- if self.index_postcodes() > 100:
- _analyze()
-
-
- def index_boundaries(self, minrank: int, maxrank: int) -> int:
- """ Index only administrative boundaries within the given rank range.
- """
- total = 0
- LOG.warning("Starting indexing boundaries using %s threads",
- self.num_threads)
-
- with self.tokenizer.name_analyzer() as analyzer:
- for rank in range(max(minrank, 4), min(maxrank, 26)):
- total += self._index(runners.BoundaryRunner(rank, analyzer))
-
- return total
-
- def index_by_rank(self, minrank: int, maxrank: int) -> int:
- """ Index all entries of placex in the given rank range (inclusive)
- in order of their address rank.
-
- When rank 30 is requested then also interpolations and
- places with address rank 0 will be indexed.
- """
- total = 0
- maxrank = min(maxrank, 30)
- LOG.warning("Starting indexing rank (%i to %i) using %i threads",
- minrank, maxrank, self.num_threads)
-
- with self.tokenizer.name_analyzer() as analyzer:
- for rank in range(max(1, minrank), maxrank + 1):
- total += self._index(runners.RankRunner(rank, analyzer), 20 if rank == 30 else 1)
-
- if maxrank == 30:
- total += self._index(runners.RankRunner(0, analyzer))
- total += self._index(runners.InterpolationRunner(analyzer), 20)
-
- return total
-
-
- def index_postcodes(self) -> int:
- """Index the entries of the location_postcode table.
- """
- LOG.warning("Starting indexing postcodes using %s threads", self.num_threads)
-
- return self._index(runners.PostcodeRunner(), 20)
-
-
- def update_status_table(self) -> None:
- """ Update the status in the status table to 'indexed'.
- """
- with connect(self.dsn) as conn:
- with conn.cursor() as cur:
- cur.execute('UPDATE import_status SET indexed = true')
-
- conn.commit()
-
- def _index(self, runner: runners.Runner, batch: int = 1) -> int:
- """ Index a single rank or table. `runner` describes the SQL to use
- for indexing. `batch` describes the number of objects that
- should be processed with a single SQL statement
- """
- LOG.warning("Starting %s (using batch size %s)", runner.name(), batch)
-
- with connect(self.dsn) as conn:
- psycopg2.extras.register_hstore(conn)
- with conn.cursor() as cur:
- total_tuples = cur.scalar(runner.sql_count_objects())
- LOG.debug("Total number of rows: %i", total_tuples)
-
- conn.commit()
-
- progress = ProgressLogger(runner.name(), total_tuples)
-
- if total_tuples > 0:
- with conn.cursor(name='places') as cur:
- cur.execute(runner.sql_get_objects())
-
- with PlaceFetcher(self.dsn, conn) as fetcher:
- with WorkerPool(self.dsn, self.num_threads) as pool:
- has_more = fetcher.fetch_next_batch(cur, runner)
- while has_more:
- places = fetcher.get_batch()
-
- # asynchronously get the next batch
- has_more = fetcher.fetch_next_batch(cur, runner)
-
- # And insert the current batch
- for idx in range(0, len(places), batch):
- part = places[idx:idx + batch]
- LOG.debug("Processing places: %s", str(part))
- runner.index_places(pool.next_free_worker(), part)
- progress.add(len(part))
-
- LOG.info("Wait time: fetcher: %.2fs, pool: %.2fs",
- fetcher.wait_time, pool.wait_time)
-
- conn.commit()
-
- return progress.done()
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2022 by the Nominatim developer community.
-# For a full list of authors see the git log.
-"""
-Mix-ins that provide the actual commands for the indexer for various indexing
-tasks.
-"""
-from typing import Any, List
-import functools
-
-from psycopg2 import sql as pysql
-import psycopg2.extras
-
-from nominatim.data.place_info import PlaceInfo
-from nominatim.tokenizer.base import AbstractAnalyzer
-from nominatim.db.async_connection import DBConnection
-from nominatim.typing import Query, DictCursorResult, DictCursorResults, Protocol
-
-# pylint: disable=C0111
-
-def _mk_valuelist(template: str, num: int) -> pysql.Composed:
- return pysql.SQL(',').join([pysql.SQL(template)] * num)
-
-def _analyze_place(place: DictCursorResult, analyzer: AbstractAnalyzer) -> psycopg2.extras.Json:
- return psycopg2.extras.Json(analyzer.process_place(PlaceInfo(place)))
-
-
-class Runner(Protocol):
- def name(self) -> str: ...
- def sql_count_objects(self) -> Query: ...
- def sql_get_objects(self) -> Query: ...
- def get_place_details(self, worker: DBConnection,
- ids: DictCursorResults) -> DictCursorResults: ...
- def index_places(self, worker: DBConnection, places: DictCursorResults) -> None: ...
-
-
-class AbstractPlacexRunner:
- """ Returns SQL commands for indexing of the placex table.
- """
- SELECT_SQL = pysql.SQL('SELECT place_id FROM placex ')
- UPDATE_LINE = "(%s, %s::hstore, %s::hstore, %s::int, %s::jsonb)"
-
- def __init__(self, rank: int, analyzer: AbstractAnalyzer) -> None:
- self.rank = rank
- self.analyzer = analyzer
-
-
- @functools.lru_cache(maxsize=1)
- def _index_sql(self, num_places: int) -> pysql.Composed:
- return pysql.SQL(
- """ UPDATE placex
- SET indexed_status = 0, address = v.addr, token_info = v.ti,
- name = v.name, linked_place_id = v.linked_place_id
- FROM (VALUES {}) as v(id, name, addr, linked_place_id, ti)
- WHERE place_id = v.id
- """).format(_mk_valuelist(AbstractPlacexRunner.UPDATE_LINE, num_places))
-
-
- def get_place_details(self, worker: DBConnection, ids: DictCursorResults) -> DictCursorResults:
- worker.perform("""SELECT place_id, extra.*
- FROM placex, LATERAL placex_indexing_prepare(placex) as extra
- WHERE place_id IN %s""",
- (tuple((p[0] for p in ids)), ))
-
- return []
-
-
- def index_places(self, worker: DBConnection, places: DictCursorResults) -> None:
- values: List[Any] = []
- for place in places:
- for field in ('place_id', 'name', 'address', 'linked_place_id'):
- values.append(place[field])
- values.append(_analyze_place(place, self.analyzer))
-
- worker.perform(self._index_sql(len(places)), values)
-
-
-class RankRunner(AbstractPlacexRunner):
- """ Returns SQL commands for indexing one rank within the placex table.
- """
-
- def name(self) -> str:
- return f"rank {self.rank}"
-
- def sql_count_objects(self) -> pysql.Composed:
- return pysql.SQL("""SELECT count(*) FROM placex
- WHERE rank_address = {} and indexed_status > 0
- """).format(pysql.Literal(self.rank))
-
- def sql_get_objects(self) -> pysql.Composed:
- return self.SELECT_SQL + pysql.SQL(
- """WHERE indexed_status > 0 and rank_address = {}
- ORDER BY geometry_sector
- """).format(pysql.Literal(self.rank))
-
-
-class BoundaryRunner(AbstractPlacexRunner):
- """ Returns SQL commands for indexing the administrative boundaries
- of a certain rank.
- """
-
- def name(self) -> str:
- return f"boundaries rank {self.rank}"
-
- def sql_count_objects(self) -> pysql.Composed:
- return pysql.SQL("""SELECT count(*) FROM placex
- WHERE indexed_status > 0
- AND rank_search = {}
- AND class = 'boundary' and type = 'administrative'
- """).format(pysql.Literal(self.rank))
-
- def sql_get_objects(self) -> pysql.Composed:
- return self.SELECT_SQL + pysql.SQL(
- """WHERE indexed_status > 0 and rank_search = {}
- and class = 'boundary' and type = 'administrative'
- ORDER BY partition, admin_level
- """).format(pysql.Literal(self.rank))
-
-
-class InterpolationRunner:
- """ Returns SQL commands for indexing the address interpolation table
- location_property_osmline.
- """
-
- def __init__(self, analyzer: AbstractAnalyzer) -> None:
- self.analyzer = analyzer
-
-
- def name(self) -> str:
- return "interpolation lines (location_property_osmline)"
-
- def sql_count_objects(self) -> str:
- return """SELECT count(*) FROM location_property_osmline
- WHERE indexed_status > 0"""
-
- def sql_get_objects(self) -> str:
- return """SELECT place_id
- FROM location_property_osmline
- WHERE indexed_status > 0
- ORDER BY geometry_sector"""
-
-
- def get_place_details(self, worker: DBConnection, ids: DictCursorResults) -> DictCursorResults:
- worker.perform("""SELECT place_id, get_interpolation_address(address, osm_id) as address
- FROM location_property_osmline WHERE place_id IN %s""",
- (tuple((p[0] for p in ids)), ))
- return []
-
-
- @functools.lru_cache(maxsize=1)
- def _index_sql(self, num_places: int) -> pysql.Composed:
- return pysql.SQL("""UPDATE location_property_osmline
- SET indexed_status = 0, address = v.addr, token_info = v.ti
- FROM (VALUES {}) as v(id, addr, ti)
- WHERE place_id = v.id
- """).format(_mk_valuelist("(%s, %s::hstore, %s::jsonb)", num_places))
-
-
- def index_places(self, worker: DBConnection, places: DictCursorResults) -> None:
- values: List[Any] = []
- for place in places:
- values.extend((place[x] for x in ('place_id', 'address')))
- values.append(_analyze_place(place, self.analyzer))
-
- worker.perform(self._index_sql(len(places)), values)
-
-
-
-class PostcodeRunner(Runner):
- """ Provides the SQL commands for indexing the location_postcode table.
- """
-
- def name(self) -> str:
- return "postcodes (location_postcode)"
-
-
- def sql_count_objects(self) -> str:
- return 'SELECT count(*) FROM location_postcode WHERE indexed_status > 0'
-
-
- def sql_get_objects(self) -> str:
- return """SELECT place_id FROM location_postcode
- WHERE indexed_status > 0
- ORDER BY country_code, postcode"""
-
-
- def get_place_details(self, worker: DBConnection, ids: DictCursorResults) -> DictCursorResults:
- return ids
-
- def index_places(self, worker: DBConnection, places: DictCursorResults) -> None:
- worker.perform(pysql.SQL("""UPDATE location_postcode SET indexed_status = 0
- WHERE place_id IN ({})""")
- .format(pysql.SQL(',').join((pysql.Literal(i[0]) for i in places))))
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2022 by the Nominatim developer community.
-# For a full list of authors see the git log.
-"""
-Path settings for extra data used by Nominatim.
-"""
-from pathlib import Path
-
-PHPLIB_DIR = (Path(__file__) / '..' / '..' / 'lib-php').resolve()
-SQLLIB_DIR = (Path(__file__) / '..' / '..' / 'lib-sql').resolve()
-DATA_DIR = (Path(__file__) / '..' / '..' / 'data').resolve()
-CONFIG_DIR = (Path(__file__) / '..' / '..' / 'settings').resolve()
--- /dev/null
+../../COPYING
\ No newline at end of file
--- /dev/null
+# Nominatim - Frontend Library
+
+Nominatim is a tool to search OpenStreetMap data
+by name and address (geocoding) and to generate synthetic addresses of
+OSM points (reverse geocoding).
+
+This module implements the library for searching a Nominatim database
+imported with the [`nominatim-db`](https://pypi.org/project/nominatim-db/) package.
+
+## Installation
+
+To install the Nominatim API from pypi, run:
+
+ pip install nominatim-api
+
+## Running a Nominatim server
+
+You need Falcon or Starlette to run Nominatim as a service, as well as
+an ASGI-capable server like uvicorn. To install them from pypi run:
+
+ pip install falcon uvicorn
+
+You need to have a Nominatim database imported with the 'nominatim-db'
+package. Go to the project directory, then run uvicorn as:
+
+ uvicorn --factory nominatim.server.falcon.server:run_wsgi
+
+## Documentation
+
+The full documentation for the Nominatim library can be found at:
+https://nominatim.org/release-docs/latest/library/Getting-Started/
+
+The v1 API of the server is documented at:
+https://nominatim.org/release-docs/latest/api/Overview/
+
+## License
+
+The source code is available under a GPLv3 license.
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Path settings for extra data used by Nominatim.
+"""
+from pathlib import Path
+
+PHPLIB_DIR = None
+DATA_DIR = None
+SQLLIB_DIR = None
+CONFIG_DIR = (Path(__file__) / '..' / 'resources' / 'settings').resolve()
--- /dev/null
+[project]
+name = "nominatim-api"
+description = "A tool for building a database of OpenStreetMap for geocoding and for searching the database. Search library."
+readme = "README.md"
+requires-python = ">=3.7"
+license = 'GPL-3.0-or-later'
+maintainers = [
+ { name = "Sarah Hoffmann", email = "lonvia@denofr.de" },
+ { name = "Marc Tobias", email = "mtmail-cpan@gmx.net" }
+]
+keywords = [ "geocoding", "OpenStreetMap", "search" ]
+classifiers = [
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: GNU General Public License (GPL)",
+ "Operating System :: OS Independent",
+]
+dependencies = [
+ "python-dotenv",
+ "pyYAML>=5.1",
+ "SQLAlchemy>=1.4.31",
+ "psycopg",
+ "PyICU"
+]
+dynamic = ["version"]
+
+[project.urls]
+Homepage = "https://nominatim.org"
+Documentation = "https://nominatim.org/release-docs/latest/"
+Issues = "https://github.com/osm-search/Nominatim/issues"
+Repository = "https://github.com/osm-search/Nominatim"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.version]
+path = "src/nominatim_api/version.py"
+pattern = "NOMINATIM_API_VERSION = '(?P<version>[^']+)'"
+
+[tool.hatch.build.targets.sdist]
+include = [
+ "src/nominatim_api",
+ "src/nominatim_db/config.py",
+ "settings",
+ "extra_src/paths.py"
+]
+
+exclude = [
+ "src/nominatim_api/config.py"
+]
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/nominatim_api"]
+
+[tool.hatch.build.targets.wheel.force-include]
+"src/nominatim_db/config.py" = "nominatim_api/config.py"
+"extra_src/paths.py" = "nominatim_api/paths.py"
+"settings" = "nominatim_api/resources/settings"
--- /dev/null
+../../settings/
\ No newline at end of file
--- /dev/null
+../../src/
\ No newline at end of file
--- /dev/null
+../../COPYING
\ No newline at end of file
--- /dev/null
+# Nominatim - DB Backend
+
+Nominatim is a tool to search OpenStreetMap data
+by name and address (geocoding) and to generate synthetic addresses of
+OSM points (reverse geocoding).
+
+This module implements the database backend for Nominatim and the
+command-line tool for importing and maintaining the database.
+
+## Installation
+
+### Prerequisites
+
+Nominatim requires [osm2pgsql](https://osm2pgsql.org/) (>=1.8) for reading
+OSM data and [PostgreSQL](https://www.postgresql.org/) (>=9.6) to store the data.
+
+On Ubuntu (>=23.04) and Debian (when using backports), you can install them with:
+
+ sudo apt-get install osm2pgsql postgresql-postgis
+
+### Installation from pypi
+
+To install Nominatim from pypi, run:
+
+ pip install nominatim-db
+
+
+## Quick start
+
+First create a project directory for your new Nominatim database, which
+is the space for additional configuration and customization:
+
+ mkdir nominatim-project
+
+Make sure you run all nominatim commands from within the project directory:
+
+ cd nominatim-project
+
+Download an appropriate data extract, for example from
+[Geofabrik](https://download.geofabrik.de/) and import the file:
+
+ nominatim import --osm-file <downlaoded-osm-data.pbf>
+
+You will need to install the [`nominatim-api`](https://pypi.org/project/nominatim-api/)
+package to query the database.
+
+## Documentation
+
+A HTML version of the documentation can be found at
+https://nominatim.org/release-docs/latest/ .
+
+## License
+
+The source code is available under a GPLv3 license.
--- /dev/null
+../../data/
\ No newline at end of file
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Path settings for extra data used by Nominatim.
+"""
+from pathlib import Path
+
+PHPLIB_DIR = None
+DATA_DIR = (Path(__file__) / '..' / 'resources').resolve()
+SQLLIB_DIR = (DATA_DIR / 'lib-sql')
+CONFIG_DIR = (DATA_DIR / 'settings')
--- /dev/null
+../../lib-sql/
\ No newline at end of file
--- /dev/null
+[project]
+name = "nominatim-db"
+description = "A tool for building a database of OpenStreetMap for geocoding and for searching the database. Database backend."
+readme = "README.md"
+requires-python = ">=3.7"
+license = 'GPL-3.0-or-later'
+maintainers = [
+ { name = "Sarah Hoffmann", email = "lonvia@denofr.de" },
+ { name = "Marc Tobias", email = "mtmail-cpan@gmx.net" }
+]
+keywords = [ "geocoding", "OpenStreetMap", "search" ]
+classifiers = [
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: GNU General Public License (GPL)",
+ "Operating System :: OS Independent",
+]
+dependencies = [
+ "psycopg",
+ "python-dotenv",
+ "jinja2",
+ "pyYAML>=5.1",
+ "datrie",
+ "psutil",
+ "PyICU"
+]
+dynamic = ["version"]
+
+[project.urls]
+Homepage = "https://nominatim.org"
+Documentation = "https://nominatim.org/release-docs/latest/"
+Issues = "https://github.com/osm-search/Nominatim/issues"
+Repository = "https://github.com/osm-search/Nominatim"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.version]
+path = "src/nominatim_db/version.py"
+pattern = "NOMINATIM_VERSION = parse_version.'(?P<version>[^-]+)"
+
+[tool.hatch.build.targets.sdist]
+include = [
+ "src/nominatim_db",
+ "scripts",
+ "lib-sql/**/*.sql",
+ "settings",
+ "data/words.sql",
+ "extra_src/nominatim_db/paths.py"
+]
+
+artifacts = [
+ "data/country_osm_grid.sql.gz"
+]
+
+exclude = [
+ "src/nominatim_db/paths.py"
+]
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/nominatim_db"]
+
+[tool.hatch.build.targets.wheel.shared-scripts]
+"scripts" = "/"
+
+[tool.hatch.build.targets.wheel.force-include]
+"lib-sql" = "nominatim_db/resources/lib-sql"
+"settings" = "nominatim_db/resources/settings"
+"data/country_osm_grid.sql.gz" = "nominatim_db/resources/country_osm_grid.sql.gz"
+"data/words.sql" = "nominatim_db/resources/words.sql"
+"extra_src/nominatim_db/paths.py" = "nominatim_db/paths.py"
--- /dev/null
+#!python3
+
+from nominatim_db import cli
+
+exit(cli.nominatim(module_dir=None, osm2pgsql_path=None))
--- /dev/null
+../../settings/
\ No newline at end of file
--- /dev/null
+../../src
\ No newline at end of file
works = 'named',
water_tower = 'always',
dyke = 'named',
+ adit = 'named',
lighthouse = 'always',
watermill = 'always',
tunnel = 'always'},
'abandoned', 'signal', 'buffer_stop', 'razed'},
aerialway = {'pylon', 'no'},
aeroway = {'no'},
- amenity = {'no', 'parking_space', 'parking_entrance'},
+ amenity = {'no', 'parking_space', 'parking_entrance',
+ 'waste_disposal', 'hunting_stand'},
club = {'no'},
craft = {'no'},
leisure = {'no'},
works = 'named',
water_tower = 'always',
dyke = 'named',
+ adit = 'named',
lighthouse = 'always',
watermill = 'always',
tunnel = 'always'},
'abandoned', 'signal', 'buffer_stop', 'razed'},
aerialway = {'pylon', 'no'},
aeroway = {'no'},
- amenity = {'no', 'parking_space', 'parking_entrance'},
+ amenity = {'no', 'parking_space', 'parking_entrance',
+ 'waste_disposal', 'hunting_stand'},
club = {'no'},
craft = {'no'},
leisure = {'no'},
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
The public interface of the Nominatim library.
# See also https://github.com/PyCQA/pylint/issues/6006
# pylint: disable=useless-import-alias
+from .errors import (UsageError as UsageError)
+from .config import (Configuration as Configuration)
+
from .core import (NominatimAPI as NominatimAPI,
NominatimAPIAsync as NominatimAPIAsync)
from .connection import (SearchConnection as SearchConnection)
SearchResult as SearchResult,
SearchResults as SearchResults)
from .localization import (Locales as Locales)
+
+from .version import NOMINATIM_API_VERSION as __version__
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+
+# This file is just a placeholder to make the config module available
+# during development. It will be replaced by nominatim_db/config.py on
+# installation.
+# pylint: skip-file
+from nominatim_db.config import *
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Extended SQLAlchemy connection class that also includes access to the schema.
import sqlalchemy as sa
from sqlalchemy.ext.asyncio import AsyncConnection
-from nominatim.typing import SaFromClause
-from nominatim.db.sqlalchemy_schema import SearchTables
-from nominatim.db.sqlalchemy_types import Geometry
-from nominatim.api.logging import log
+from .typing import SaFromClause
+from .sql.sqlalchemy_schema import SearchTables
+from .sql.sqlalchemy_types import Geometry
+from .logging import log
T = TypeVar('T')
class SearchConnection:
""" An extended SQLAlchemy connection class, that also contains
- then table definitions. The underlying asynchronous SQLAlchemy
+ the table definitions. The underlying asynchronous SQLAlchemy
connection can be accessed with the 'connection' property.
The 't' property is the collection of Nominatim tables.
"""
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of classes for API access via libraries.
"""
-from typing import Mapping, Optional, Any, AsyncIterator, Dict, Sequence, List, Tuple
+from typing import Mapping, Optional, Any, AsyncIterator, Dict, Sequence, List, Tuple, cast
import asyncio
import sys
import contextlib
import sqlalchemy as sa
import sqlalchemy.ext.asyncio as sa_asyncio
-from nominatim.errors import UsageError
-from nominatim.db.sqlalchemy_schema import SearchTables
-from nominatim.db.async_core_library import PGCORE_LIB, PGCORE_ERROR
-import nominatim.db.sqlite_functions
-from nominatim.config import Configuration
-from nominatim.api.connection import SearchConnection
-from nominatim.api.status import get_status, StatusResult
-from nominatim.api.lookup import get_detailed_place, get_simple_place
-from nominatim.api.reverse import ReverseGeocoder
-from nominatim.api.search import ForwardGeocoder, Phrase, PhraseType, make_query_analyzer
-import nominatim.api.types as ntyp
-from nominatim.api.results import DetailedResult, ReverseResult, SearchResults
+from .errors import UsageError
+from .sql.sqlalchemy_schema import SearchTables
+from .sql.async_core_library import PGCORE_LIB, PGCORE_ERROR
+from .config import Configuration
+from .sql import sqlite_functions, sqlalchemy_functions #pylint: disable=unused-import
+from .connection import SearchConnection
+from .status import get_status, StatusResult
+from .lookup import get_detailed_place, get_simple_place
+from .reverse import ReverseGeocoder
+from .search import ForwardGeocoder, Phrase, PhraseType, make_query_analyzer
+from . import types as ntyp
+from .results import DetailedResult, ReverseResult, SearchResults
class NominatimAPIAsync: #pylint: disable=too-many-instance-attributes
raise UsageError(f"SQlite database '{params.get('dbname')}' does not exist.")
else:
dsn = self.config.get_database_params()
- query = {k: v for k, v in dsn.items()
+ query = {k: str(v) for k, v in dsn.items()
if k not in ('user', 'password', 'dbname', 'host', 'port')}
dburl = sa.engine.URL.create(
f'postgresql+{PGCORE_LIB}',
- database=dsn.get('dbname'),
- username=dsn.get('user'),
- password=dsn.get('password'),
- host=dsn.get('host'),
- port=int(dsn['port']) if 'port' in dsn else None,
+ database=cast(str, dsn.get('dbname')),
+ username=cast(str, dsn.get('user')),
+ password=cast(str, dsn.get('password')),
+ host=cast(str, dsn.get('host')),
+ port=int(cast(str, dsn['port'])) if 'port' in dsn else None,
query=query)
engine = sa_asyncio.create_async_engine(dburl, **extra_args)
@sa.event.listens_for(engine.sync_engine, "connect")
def _on_sqlite_connect(dbapi_con: Any, _: Any) -> None:
dbapi_con.run_async(lambda conn: conn.enable_load_extension(True))
- nominatim.db.sqlite_functions.install_custom_functions(dbapi_con)
+ sqlite_functions.install_custom_functions(dbapi_con)
cursor = dbapi_con.cursor()
cursor.execute("SELECT load_extension('mod_spatialite')")
cursor.execute('SELECT SetDecimalPrecision(7)')
@property
def config(self) -> Configuration:
- """ Provide read-only access to the [configuration](#Configuration)
+ """ Provide read-only access to the [configuration](Configuration.md)
used by the API.
"""
return self._async_api.config
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Custom exception and error classes for Nominatim.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper functions for localizing names of results.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for specialised logging with HTML output.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of place lookup by ID.
import sqlalchemy as sa
-from nominatim.typing import SaColumn, SaRow, SaSelect
-from nominatim.api.connection import SearchConnection
-import nominatim.api.types as ntyp
-import nominatim.api.results as nres
-from nominatim.api.logging import log
+from .typing import SaColumn, SaRow, SaSelect
+from .connection import SearchConnection
+from .logging import log
+from . import types as ntyp
+from . import results as nres
RowFunc = Callable[[Optional[SaRow], Type[nres.BaseResultT]], Optional[nres.BaseResultT]]
GeomFunc = Callable[[SaSelect, SaColumn], SaSelect]
-
async def find_in_placex(conn: SearchConnection, place: ntyp.PlaceRef,
add_geometries: GeomFunc) -> Optional[SaRow]:
""" Search for the given place in the placex table and return the
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper classes and functions for formatting results into API responses.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Dataclasses for search results and helper functions to fill them.
import sqlalchemy as sa
-from nominatim.typing import SaSelect, SaRow
-from nominatim.db.sqlalchemy_types import Geometry
-from nominatim.api.types import Point, Bbox, LookupDetails
-from nominatim.api.connection import SearchConnection
-from nominatim.api.logging import log
-from nominatim.api.localization import Locales
+from .typing import SaSelect, SaRow
+from .sql.sqlalchemy_types import Geometry
+from .types import Point, Bbox, LookupDetails
+from .connection import SearchConnection
+from .logging import log
+from .localization import Locales
# This file defines complex result data classes.
# pylint: disable=too-many-instance-attributes
local_name: Optional[str] = None
""" Place holder for localization of this address part. See
- [Localization](#localization) below.
+ [Localization](Result-Handling.md#localization) below.
"""
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of reverse geocoding.
import sqlalchemy as sa
-from nominatim.typing import SaColumn, SaSelect, SaFromClause, SaLabel, SaRow,\
- SaBind, SaLambdaSelect
-from nominatim.api.connection import SearchConnection
-import nominatim.api.results as nres
-from nominatim.api.logging import log
-from nominatim.api.types import AnyPoint, DataLayer, ReverseDetails, GeometryFormat, Bbox
-from nominatim.db.sqlalchemy_types import Geometry
+from .typing import SaColumn, SaSelect, SaFromClause, SaLabel, SaRow,\
+ SaBind, SaLambdaSelect
+from .sql.sqlalchemy_types import Geometry
+from .connection import SearchConnection
+from . import results as nres
+from .logging import log
+from .types import AnyPoint, DataLayer, ReverseDetails, GeometryFormat, Bbox
# In SQLAlchemy expression which compare with NULL need to be expressed with
# the equal sign.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module for forward search.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Conversion from token assignment to an abstract DB search.
from typing import Optional, List, Tuple, Iterator, Dict
import heapq
-from nominatim.api.types import SearchDetails, DataLayer
-from nominatim.api.search.query import QueryStruct, Token, TokenType, TokenRange, BreakType
-from nominatim.api.search.token_assignment import TokenAssignment
-import nominatim.api.search.db_search_fields as dbf
-import nominatim.api.search.db_searches as dbs
-import nominatim.api.search.db_search_lookups as lookups
+from ..types import SearchDetails, DataLayer
+from .query import QueryStruct, Token, TokenType, TokenRange, BreakType
+from .token_assignment import TokenAssignment
+from . import db_search_fields as dbf
+from . import db_searches as dbs
+from . import db_search_lookups as lookups
def wrap_near_search(categories: List[Tuple[str, str]],
expected_count = sum(t.count for t in hnrs)
partials = {t.token: t.addr_count for trange in address
- for t in self.query.get_partials_list(trange)}
+ for t in self.query.get_partials_list(trange)
+ if t.is_indexed}
+
+ if not partials:
+ # can happen when none of the partials is indexed
+ return
if expected_count < 8000:
sdata.lookups.append(dbf.FieldLookup('nameaddress_vector',
use_lookup: bool) -> List[dbf.FieldLookup]:
""" Create a ranking expression with full name terms and
additional address lookup. When 'use_lookup' is true, then
- address lookups will use the index, when the occurences are not
+ address lookups will use the index, when the occurrences are not
too many.
"""
# At this point drop unindexed partials from the address.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Data structures for more complex fields in abstract search descriptions.
import sqlalchemy as sa
-from nominatim.typing import SaFromClause, SaColumn, SaExpression
-from nominatim.api.search.query import Token
-import nominatim.api.search.db_search_lookups as lookups
-from nominatim.utils.json_writer import JsonWriter
+from ..typing import SaFromClause, SaColumn, SaExpression
+from ..utils.json_writer import JsonWriter
+from .query import Token
+from . import db_search_lookups as lookups
@dataclasses.dataclass
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of lookup functions for the search_name table.
import sqlalchemy as sa
from sqlalchemy.ext.compiler import compiles
-from nominatim.typing import SaFromClause
-from nominatim.db.sqlalchemy_types import IntArray
+from ..typing import SaFromClause
+from ..sql.sqlalchemy_types import IntArray
# pylint: disable=consider-using-f-string
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the actual database accesses for forward search.
import sqlalchemy as sa
-from nominatim.typing import SaFromClause, SaScalarSelect, SaColumn, \
- SaExpression, SaSelect, SaLambdaSelect, SaRow, SaBind
-from nominatim.api.connection import SearchConnection
-from nominatim.api.types import SearchDetails, DataLayer, GeometryFormat, Bbox
-import nominatim.api.results as nres
-from nominatim.api.search.db_search_fields import SearchData, WeightedCategories
-from nominatim.db.sqlalchemy_types import Geometry, IntArray
+from ..typing import SaFromClause, SaScalarSelect, SaColumn, \
+ SaExpression, SaSelect, SaLambdaSelect, SaRow, SaBind
+from ..sql.sqlalchemy_types import Geometry, IntArray
+from ..connection import SearchConnection
+from ..types import SearchDetails, DataLayer, GeometryFormat, Bbox
+from .. import results as nres
+from .db_search_fields import SearchData, WeightedCategories
#pylint: disable=singleton-comparison,not-callable
#pylint: disable=too-many-branches,too-many-arguments,too-many-locals,too-many-statements
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Public interface to the search code.
import datetime as dt
import difflib
-from nominatim.api.connection import SearchConnection
-from nominatim.api.types import SearchDetails
-from nominatim.api.results import SearchResult, SearchResults, add_result_details
-from nominatim.api.search.token_assignment import yield_token_assignments
-from nominatim.api.search.db_search_builder import SearchBuilder, build_poi_search, wrap_near_search
-from nominatim.api.search.db_searches import AbstractSearch
-from nominatim.api.search.query_analyzer_factory import make_query_analyzer, AbstractQueryAnalyzer
-from nominatim.api.search.query import Phrase, QueryStruct
-from nominatim.api.logging import log
+from ..connection import SearchConnection
+from ..types import SearchDetails
+from ..results import SearchResult, SearchResults, add_result_details
+from ..logging import log
+from .token_assignment import yield_token_assignments
+from .db_search_builder import SearchBuilder, build_poi_search, wrap_near_search
+from .db_searches import AbstractSearch
+from .query_analyzer_factory import make_query_analyzer, AbstractQueryAnalyzer
+from .query import Phrase, QueryStruct
class ForwardGeocoder:
""" Main class responsible for place search.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of query analysis for the ICU tokenizer.
import sqlalchemy as sa
-from nominatim.typing import SaRow
-from nominatim.api.connection import SearchConnection
-from nominatim.api.logging import log
-from nominatim.api.search import query as qmod
-from nominatim.api.search.query_analyzer_factory import AbstractQueryAnalyzer
-from nominatim.db.sqlalchemy_types import Json
+from ..typing import SaRow
+from ..sql.sqlalchemy_types import Json
+from ..connection import SearchConnection
+from ..logging import log
+from ..search import query as qmod
+from ..search.query_analyzer_factory import AbstractQueryAnalyzer
DB_TO_TOKEN_TYPE = {
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of query analysis for the legacy tokenizer.
import sqlalchemy as sa
-from nominatim.typing import SaRow
-from nominatim.api.connection import SearchConnection
-from nominatim.api.logging import log
-from nominatim.api.search import query as qmod
-from nominatim.api.search.query_analyzer_factory import AbstractQueryAnalyzer
+from ..typing import SaRow
+from ..connection import SearchConnection
+from ..logging import log
+from . import query as qmod
+from .query_analyzer_factory import AbstractQueryAnalyzer
def yield_words(terms: List[str], start: int) -> Iterator[Tuple[str, qmod.TokenRange]]:
""" Return all combinations of words in the terms list after the
lookup_word = row.word_token[1:]
elif rowclass == 'place' and row.type == 'postcode':
ttype = qmod.TokenType.POSTCODE
- lookup_word = row.word_token[1:]
+ lookup_word = row.word
else:
ttype = qmod.TokenType.NEAR_ITEM if row.operator in ('in', 'near')\
else qmod.TokenType.QUALIFIER
def _dump_word_tokens(query: qmod.QueryStruct) -> Iterator[List[Any]]:
- yield ['type', 'token', 'word_token', 'lookup_word', 'penalty', 'count', 'info']
+ yield ['type', 'token', 'word_token', 'lookup_word', 'penalty', 'count', 'info', 'indexed']
for node in query.nodes:
for tlist in node.starting:
for token in tlist.tokens:
t = cast(LegacyToken, token)
yield [tlist.ttype.name, t.token, t.word_token or '',
- t.lookup_word or '', t.penalty, t.count, t.info]
+ t.lookup_word or '', t.penalty, t.count, t.info,
+ 'Y' if t.is_indexed else 'N']
async def create_query_analyzer(conn: SearchConnection) -> AbstractQueryAnalyzer:
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Datastructures for a tokenized query.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Factory for creating a query analyzer for the configured tokenizer.
from pathlib import Path
import importlib
-from nominatim.api.logging import log
-from nominatim.api.connection import SearchConnection
+from ..logging import log
+from ..connection import SearchConnection
if TYPE_CHECKING:
- from nominatim.api.search.query import Phrase, QueryStruct
+ from .query import Phrase, QueryStruct
class AbstractQueryAnalyzer(ABC):
""" Class for analysing incoming queries.
log().comment(f"No tokenizer named '{name}' available. Database not set up properly.")
raise RuntimeError('Tokenizer not found')
- module = importlib.import_module(f'nominatim.api.search.{name}_tokenizer')
+ module = importlib.import_module(f'nominatim_api.search.{name}_tokenizer')
return cast(AbstractQueryAnalyzer, await module.create_query_analyzer(conn))
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Create query interpretations where each vertice in the query is assigned
from typing import Optional, List, Iterator
import dataclasses
-import nominatim.api.search.query as qmod
-from nominatim.api.logging import log
+from ..logging import log
+from . import query as qmod
# pylint: disable=too-many-return-statements,too-many-branches
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Server implementation using the falcon webserver framework.
from falcon.asgi import App, Request, Response
-from nominatim.api import NominatimAPIAsync
-import nominatim.api.v1 as api_impl
-import nominatim.api.logging as loglib
-from nominatim.config import Configuration
+from ...config import Configuration
+from ...core import NominatimAPIAsync
+from ... import v1 as api_impl
+from ... import logging as loglib
class HTTPNominatimError(Exception):
""" A special exception class for errors raised during processing.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Server implementation using the starlette webserver framework.
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.middleware.cors import CORSMiddleware
-from nominatim.api import NominatimAPIAsync
-import nominatim.api.v1 as api_impl
-import nominatim.api.logging as loglib
-from nominatim.config import Configuration
+from ...config import Configuration
+from ...core import NominatimAPIAsync
+from ... import v1 as api_impl
+from ... import logging as loglib
class ParamWrapper(api_impl.ASGIAdaptor):
""" Adaptor class for server glue to Starlette framework.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Import the base library to use with asynchronous SQLAlchemy.
"""
-# pylint: disable=invalid-name
+# pylint: disable=invalid-name, ungrouped-imports, unused-import
from typing import Any
try:
+ import sqlalchemy.dialects.postgresql.psycopg
import psycopg
PGCORE_LIB = 'psycopg'
PGCORE_ERROR: Any = psycopg.Error
except ModuleNotFoundError:
+ import sqlalchemy.dialects.postgresql.asyncpg
import asyncpg
PGCORE_LIB = 'asyncpg'
PGCORE_ERROR = asyncpg.PostgresError
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Custom functions and expressions for SQLAlchemy.
import sqlalchemy as sa
from sqlalchemy.ext.compiler import compiles
-from nominatim.typing import SaColumn
+from ..typing import SaColumn
# pylint: disable=all
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
SQLAlchemy definitions for all tables used by the frontend.
"""
import sqlalchemy as sa
-import nominatim.db.sqlalchemy_functions #pylint: disable=unused-import
-from nominatim.db.sqlalchemy_types import Geometry, KeyValueStore, IntArray
+from .sqlalchemy_types import Geometry, KeyValueStore, IntArray
#pylint: disable=too-many-instance-attributes
class SearchTables:
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module with custom types for SQLAlchemy
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Custom types for SQLAlchemy.
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import types
-from nominatim.typing import SaColumn, SaBind
+from ...typing import SaColumn, SaBind
#pylint: disable=all
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Custom type for an array of integers.
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.dialects.postgresql import ARRAY
-from nominatim.typing import SaDialect, SaColumn
+from ...typing import SaDialect, SaColumn
# pylint: disable=all
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Common json type for different dialects.
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.dialects.sqlite import JSON as sqlite_json
-from nominatim.typing import SaDialect
+from ...typing import SaDialect
# pylint: disable=all
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
A custom type that implements a simple key-value store of strings.
from sqlalchemy.dialects.postgresql import HSTORE
from sqlalchemy.dialects.sqlite import JSON as sqlite_json
-from nominatim.typing import SaDialect, SaColumn
+from ...typing import SaDialect, SaColumn
# pylint: disable=all
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Custom functions for SQLite.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Classes and function related to status call.
import sqlalchemy as sa
-from nominatim.api.connection import SearchConnection
-from nominatim import version
+from .connection import SearchConnection
+from .version import NOMINATIM_API_VERSION
@dataclasses.dataclass
class StatusResult:
"""
status: int
message: str
- software_version = version.NOMINATIM_VERSION
+ software_version = NOMINATIM_API_VERSION
data_updated: Optional[dt.datetime] = None
- database_version: Optional[version.NominatimVersion] = None
+ database_version: Optional[str] = None
async def get_status(conn: SearchConnection) -> StatusResult:
# Database version
try:
- verstr = await conn.get_property('database_version')
- status.database_version = version.parse_version(verstr)
+ status.database_version = await conn.get_property('database_version')
except ValueError:
pass
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Complex datatypes used by the Nominatim API.
from struct import unpack
from binascii import unhexlify
-from nominatim.errors import UsageError
-from nominatim.api.localization import Locales
+from .errors import UsageError
+from .localization import Locales
# pylint: disable=no-member,too-many-boolean-expressions,too-many-instance-attributes
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Type definitions for typing annotations.
+
+Complex type definitions are moved here, to keep the source files readable.
+"""
+from typing import Union, TYPE_CHECKING
+
+# pylint: disable=missing-class-docstring,useless-import-alias
+
+# SQLAlchemy introduced generic types in version 2.0 making typing
+# incompatible with older versions. Add wrappers here so we don't have
+# to litter the code with bare-string types.
+
+if TYPE_CHECKING:
+ from typing import Any
+ import sqlalchemy as sa
+ import os
+ from typing_extensions import (TypeAlias as TypeAlias)
+else:
+ TypeAlias = str
+
+StrPath = Union[str, 'os.PathLike[str]']
+
+SaLambdaSelect: TypeAlias = 'Union[sa.Select[Any], sa.StatementLambdaElement]'
+SaSelect: TypeAlias = 'sa.Select[Any]'
+SaScalarSelect: TypeAlias = 'sa.ScalarSelect[Any]'
+SaRow: TypeAlias = 'sa.Row[Any]'
+SaColumn: TypeAlias = 'sa.ColumnElement[Any]'
+SaExpression: TypeAlias = 'sa.ColumnElement[bool]'
+SaLabel: TypeAlias = 'sa.Label[Any]'
+SaFromClause: TypeAlias = 'sa.FromClause'
+SaSelectable: TypeAlias = 'sa.Selectable'
+SaBind: TypeAlias = 'sa.BindParameter[Any]'
+SaDialect: TypeAlias = 'sa.Dialect'
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Streaming JSON encoder.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of API version v1 (aka the legacy version).
#pylint: disable=useless-import-alias
-from nominatim.api.v1.server_glue import (ASGIAdaptor as ASGIAdaptor,
- EndpointFunc as EndpointFunc,
- ROUTES as ROUTES)
+from .server_glue import (ASGIAdaptor as ASGIAdaptor,
+ EndpointFunc as EndpointFunc,
+ ROUTES as ROUTES)
-import nominatim.api.v1.format as _format
+from . import format as _format
list_formats = _format.dispatch.list_formats
supports_format = _format.dispatch.supports_format
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Hard-coded information about tag categories.
"""
from typing import Tuple, Optional, Mapping, Union
-import nominatim.api as napi
+from ..results import ReverseResult, SearchResult
+from ..types import Bbox
def get_label_tag(category: Tuple[str, str], extratags: Optional[Mapping[str, str]],
rank: int, country: Optional[str]) -> str:
return label.lower().replace(' ', '_')
-def bbox_from_result(result: Union[napi.ReverseResult, napi.SearchResult]) -> napi.Bbox:
+def bbox_from_result(result: Union[ReverseResult, SearchResult]) -> Bbox:
""" Compute a bounding box for the result. For ways and relations
a given boundingbox is used. For all other object, a box is computed
around the centroid according to dimensions derived from the
"""
if (result.osm_object and result.osm_object[0] == 'N') or result.bbox is None:
extent = NODE_EXTENT.get(result.category, 0.00005)
- return napi.Bbox.from_point(result.centroid, extent)
+ return Bbox.from_point(result.centroid, extent)
return result.bbox
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Output formatters for API version v1.
import collections
import datetime as dt
-import nominatim.api as napi
-from nominatim.api.result_formatting import FormatDispatcher
-from nominatim.api.v1.classtypes import ICONS
-from nominatim.api.v1 import format_json, format_xml
-from nominatim.utils.json_writer import JsonWriter
+from ..utils.json_writer import JsonWriter
+from ..status import StatusResult
+from ..results import DetailedResult, ReverseResults, SearchResults, \
+ AddressLines, AddressLine
+from ..localization import Locales
+from ..result_formatting import FormatDispatcher
+from .classtypes import ICONS
+from . import format_json, format_xml
class RawDataList(List[Dict[str, Any]]):
""" Data type for formatting raw data lists 'as is' in json.
dispatch = FormatDispatcher()
-@dispatch.format_func(napi.StatusResult, 'text')
-def _format_status_text(result: napi.StatusResult, _: Mapping[str, Any]) -> str:
+@dispatch.format_func(StatusResult, 'text')
+def _format_status_text(result: StatusResult, _: Mapping[str, Any]) -> str:
if result.status:
return f"ERROR: {result.message}"
return 'OK'
-@dispatch.format_func(napi.StatusResult, 'json')
-def _format_status_json(result: napi.StatusResult, _: Mapping[str, Any]) -> str:
+@dispatch.format_func(StatusResult, 'json')
+def _format_status_json(result: StatusResult, _: Mapping[str, Any]) -> str:
out = JsonWriter()
out.start_object()\
return out()
-def _add_address_row(writer: JsonWriter, row: napi.AddressLine,
- locales: napi.Locales) -> None:
+def _add_address_row(writer: JsonWriter, row: AddressLine,
+ locales: Locales) -> None:
writer.start_object()\
.keyval('localname', locales.display_name(row.names))\
.keyval_not_none('place_id', row.place_id)
.end_object()
-def _add_address_rows(writer: JsonWriter, section: str, rows: napi.AddressLines,
- locales: napi.Locales) -> None:
+def _add_address_rows(writer: JsonWriter, section: str, rows: AddressLines,
+ locales: Locales) -> None:
writer.key(section).start_array()
for row in rows:
_add_address_row(writer, row, locales)
writer.end_array().next()
-def _add_parent_rows_grouped(writer: JsonWriter, rows: napi.AddressLines,
- locales: napi.Locales) -> None:
+def _add_parent_rows_grouped(writer: JsonWriter, rows: AddressLines,
+ locales: Locales) -> None:
# group by category type
data = collections.defaultdict(list)
for row in rows:
writer.end_object().next()
-@dispatch.format_func(napi.DetailedResult, 'json')
-def _format_details_json(result: napi.DetailedResult, options: Mapping[str, Any]) -> str:
- locales = options.get('locales', napi.Locales())
+@dispatch.format_func(DetailedResult, 'json')
+def _format_details_json(result: DetailedResult, options: Mapping[str, Any]) -> str:
+ locales = options.get('locales', Locales())
geom = result.geometry.get('geojson')
centroid = result.centroid.to_geojson()
return out()
-@dispatch.format_func(napi.ReverseResults, 'xml')
-def _format_reverse_xml(results: napi.ReverseResults, options: Mapping[str, Any]) -> str:
+@dispatch.format_func(ReverseResults, 'xml')
+def _format_reverse_xml(results: ReverseResults, options: Mapping[str, Any]) -> str:
return format_xml.format_base_xml(results,
options, True, 'reversegeocode',
{'querystring': options.get('query', '')})
-@dispatch.format_func(napi.ReverseResults, 'geojson')
-def _format_reverse_geojson(results: napi.ReverseResults,
+@dispatch.format_func(ReverseResults, 'geojson')
+def _format_reverse_geojson(results: ReverseResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_geojson(results, options, True)
-@dispatch.format_func(napi.ReverseResults, 'geocodejson')
-def _format_reverse_geocodejson(results: napi.ReverseResults,
+@dispatch.format_func(ReverseResults, 'geocodejson')
+def _format_reverse_geocodejson(results: ReverseResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_geocodejson(results, options, True)
-@dispatch.format_func(napi.ReverseResults, 'json')
-def _format_reverse_json(results: napi.ReverseResults,
+@dispatch.format_func(ReverseResults, 'json')
+def _format_reverse_json(results: ReverseResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_json(results, options, True,
class_label='class')
-@dispatch.format_func(napi.ReverseResults, 'jsonv2')
-def _format_reverse_jsonv2(results: napi.ReverseResults,
+@dispatch.format_func(ReverseResults, 'jsonv2')
+def _format_reverse_jsonv2(results: ReverseResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_json(results, options, True,
class_label='category')
-@dispatch.format_func(napi.SearchResults, 'xml')
-def _format_search_xml(results: napi.SearchResults, options: Mapping[str, Any]) -> str:
+@dispatch.format_func(SearchResults, 'xml')
+def _format_search_xml(results: SearchResults, options: Mapping[str, Any]) -> str:
extra = {'querystring': options.get('query', '')}
for attr in ('more_url', 'exclude_place_ids', 'viewbox'):
if options.get(attr):
-@dispatch.format_func(napi.SearchResults, 'geojson')
-def _format_search_geojson(results: napi.SearchResults,
+@dispatch.format_func(SearchResults, 'geojson')
+def _format_search_geojson(results: SearchResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_geojson(results, options, False)
-@dispatch.format_func(napi.SearchResults, 'geocodejson')
-def _format_search_geocodejson(results: napi.SearchResults,
+@dispatch.format_func(SearchResults, 'geocodejson')
+def _format_search_geocodejson(results: SearchResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_geocodejson(results, options, False)
-@dispatch.format_func(napi.SearchResults, 'json')
-def _format_search_json(results: napi.SearchResults,
+@dispatch.format_func(SearchResults, 'json')
+def _format_search_json(results: SearchResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_json(results, options, False,
class_label='class')
-@dispatch.format_func(napi.SearchResults, 'jsonv2')
-def _format_search_jsonv2(results: napi.SearchResults,
+@dispatch.format_func(SearchResults, 'jsonv2')
+def _format_search_jsonv2(results: SearchResults,
options: Mapping[str, Any]) -> str:
return format_json.format_base_json(results, options, False,
class_label='category')
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper functions for output of results in json formats.
"""
from typing import Mapping, Any, Optional, Tuple, Union
-import nominatim.api as napi
-import nominatim.api.v1.classtypes as cl
-from nominatim.utils.json_writer import JsonWriter
+from ..utils.json_writer import JsonWriter
+from ..results import AddressLines, ReverseResults, SearchResults
+from . import classtypes as cl
#pylint: disable=too-many-branches
.keyval('osm_id', osm_object[1])
-def _write_typed_address(out: JsonWriter, address: Optional[napi.AddressLines],
+def _write_typed_address(out: JsonWriter, address: Optional[AddressLines],
country_code: Optional[str]) -> None:
parts = {}
for line in (address or []):
def _write_geocodejson_address(out: JsonWriter,
- address: Optional[napi.AddressLines],
+ address: Optional[AddressLines],
obj_place_id: Optional[int],
country_code: Optional[str]) -> None:
extra = {}
out.keyval('country_code', country_code)
-def format_base_json(results: Union[napi.ReverseResults, napi.SearchResults],
+def format_base_json(results: Union[ReverseResults, SearchResults],
options: Mapping[str, Any], simple: bool,
class_label: str) -> str:
""" Return the result list as a simple json string in custom Nominatim format.
return out()
-def format_base_geojson(results: Union[napi.ReverseResults, napi.SearchResults],
+def format_base_geojson(results: Union[ReverseResults, SearchResults],
options: Mapping[str, Any],
simple: bool) -> str:
""" Return the result list as a geojson string.
return out()
-def format_base_geocodejson(results: Union[napi.ReverseResults, napi.SearchResults],
+def format_base_geocodejson(results: Union[ReverseResults, SearchResults],
options: Mapping[str, Any], simple: bool) -> str:
""" Return the result list as a geocodejson string.
"""
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper functions for output of results in XML format.
import datetime as dt
import xml.etree.ElementTree as ET
-import nominatim.api as napi
-import nominatim.api.v1.classtypes as cl
+from ..results import AddressLines, ReverseResult, ReverseResults, \
+ SearchResult, SearchResults
+from . import classtypes as cl
#pylint: disable=too-many-branches
-def _write_xml_address(root: ET.Element, address: napi.AddressLines,
+def _write_xml_address(root: ET.Element, address: AddressLines,
country_code: Optional[str]) -> None:
parts = {}
for line in address:
ET.SubElement(root, 'country_code').text = country_code
-def _create_base_entry(result: Union[napi.ReverseResult, napi.SearchResult],
+def _create_base_entry(result: Union[ReverseResult, SearchResult],
root: ET.Element, simple: bool) -> ET.Element:
place = ET.SubElement(root, 'result' if simple else 'place')
if result.place_id is not None:
return place
-def format_base_xml(results: Union[napi.ReverseResults, napi.SearchResults],
+def format_base_xml(results: Union[ReverseResults, SearchResults],
options: Mapping[str, Any],
simple: bool, xml_root_tag: str,
xml_extra_info: Mapping[str, str]) -> str:
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper function for parsing parameters and and outputting data
from itertools import chain
import re
-from nominatim.api.results import SearchResult, SearchResults, SourceTable
-from nominatim.api.types import SearchDetails, GeometryFormat
+from ..results import SearchResult, SearchResults, SourceTable
+from ..types import SearchDetails, GeometryFormat
REVERSE_MAX_RANKS = [2, 2, 2, # 0-2 Continent/Sea
4, 4, # 3-4 Country
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Generic part of the server implementation of the v1 API.
import sqlalchemy as sa
-from nominatim.errors import UsageError
-from nominatim.config import Configuration
-import nominatim.api as napi
-import nominatim.api.logging as loglib
-from nominatim.api.v1.format import dispatch as formatting
-from nominatim.api.v1.format import RawDataList
-from nominatim.api.v1 import helpers
+from ..errors import UsageError
+from ..config import Configuration
+from .. import logging as loglib
+from ..core import NominatimAPIAsync
+from .format import dispatch as formatting
+from .format import RawDataList
+from ..types import DataLayer, GeometryFormat, PlaceRef, PlaceID, OsmID, Point
+from ..status import StatusResult
+from ..results import DetailedResult, ReverseResults, SearchResult, SearchResults
+from ..localization import Locales
+from . import helpers
CONTENT_TEXT = 'text/plain; charset=utf-8'
CONTENT_XML = 'text/xml; charset=utf-8'
return False
- def get_layers(self) -> Optional[napi.DataLayer]:
+ def get_layers(self) -> Optional[DataLayer]:
""" Return a parsed version of the layer parameter.
"""
param = self.get('layer', None)
if param is None:
return None
- return cast(napi.DataLayer,
- reduce(napi.DataLayer.__or__,
- (getattr(napi.DataLayer, s.upper()) for s in param.split(','))))
+ return cast(DataLayer,
+ reduce(DataLayer.__or__,
+ (getattr(DataLayer, s.upper()) for s in param.split(','))))
def parse_format(self, result_type: Type[Any], default: str) -> str:
""" Create details structure from the supplied geometry parameters.
"""
numgeoms = 0
- output = napi.GeometryFormat.NONE
+ output = GeometryFormat.NONE
if self.get_bool('polygon_geojson', False):
- output |= napi.GeometryFormat.GEOJSON
+ output |= GeometryFormat.GEOJSON
numgeoms += 1
if fmt not in ('geojson', 'geocodejson'):
if self.get_bool('polygon_text', False):
- output |= napi.GeometryFormat.TEXT
+ output |= GeometryFormat.TEXT
numgeoms += 1
if self.get_bool('polygon_kml', False):
- output |= napi.GeometryFormat.KML
+ output |= GeometryFormat.KML
numgeoms += 1
if self.get_bool('polygon_svg', False):
- output |= napi.GeometryFormat.SVG
+ output |= GeometryFormat.SVG
numgeoms += 1
if numgeoms > self.config().get_int('POLYGON_OUTPUT_MAX_TYPES'):
}
-async def status_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def status_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /status endpoint. See API docs for details.
"""
result = await api.status()
- fmt = params.parse_format(napi.StatusResult, 'text')
+ fmt = params.parse_format(StatusResult, 'text')
if fmt == 'text' and result.status:
status_code = 500
status=status_code)
-async def details_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def details_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /details endpoint. See API docs for details.
"""
- fmt = params.parse_format(napi.DetailedResult, 'json')
+ fmt = params.parse_format(DetailedResult, 'json')
place_id = params.get_int('place_id', 0)
- place: napi.PlaceRef
+ place: PlaceRef
if place_id:
- place = napi.PlaceID(place_id)
+ place = PlaceID(place_id)
else:
osmtype = params.get('osmtype')
if osmtype is None:
params.raise_error("Missing ID parameter 'place_id' or 'osmtype'.")
- place = napi.OsmID(osmtype, params.get_int('osmid'), params.get('class'))
+ place = OsmID(osmtype, params.get_int('osmid'), params.get('class'))
debug = params.setup_debugging()
- locales = napi.Locales.from_accept_languages(params.get_accepted_languages())
+ locales = Locales.from_accept_languages(params.get_accepted_languages())
result = await api.details(place,
address_details=params.get_bool('addressdetails', False),
linked_places=params.get_bool('linkedplaces', True),
parented_places=params.get_bool('hierarchy', False),
keywords=params.get_bool('keywords', False),
- geometry_output = napi.GeometryFormat.GEOJSON
+ geometry_output = GeometryFormat.GEOJSON
if params.get_bool('polygon_geojson', False)
- else napi.GeometryFormat.NONE,
+ else GeometryFormat.NONE,
locales=locales
)
return params.build_response(output, num_results=1)
-async def reverse_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def reverse_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /reverse endpoint. See API docs for details.
"""
- fmt = params.parse_format(napi.ReverseResults, 'xml')
+ fmt = params.parse_format(ReverseResults, 'xml')
debug = params.setup_debugging()
- coord = napi.Point(params.get_float('lon'), params.get_float('lat'))
+ coord = Point(params.get_float('lon'), params.get_float('lat'))
details = params.parse_geometry_details(fmt)
details['max_rank'] = helpers.zoom_to_rank(params.get_int('zoom', 18))
details['layers'] = params.get_layers()
- details['locales'] = napi.Locales.from_accept_languages(params.get_accepted_languages())
+ details['locales'] = Locales.from_accept_languages(params.get_accepted_languages())
result = await api.reverse(coord, **details)
'namedetails': params.get_bool('namedetails', False),
'addressdetails': params.get_bool('addressdetails', True)}
- output = formatting.format_result(napi.ReverseResults([result] if result else []),
+ output = formatting.format_result(ReverseResults([result] if result else []),
fmt, fmt_options)
return params.build_response(output, num_results=1 if result else 0)
-async def lookup_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def lookup_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /lookup endpoint. See API docs for details.
"""
- fmt = params.parse_format(napi.SearchResults, 'xml')
+ fmt = params.parse_format(SearchResults, 'xml')
debug = params.setup_debugging()
details = params.parse_geometry_details(fmt)
- details['locales'] = napi.Locales.from_accept_languages(params.get_accepted_languages())
+ details['locales'] = Locales.from_accept_languages(params.get_accepted_languages())
places = []
for oid in (params.get('osm_ids') or '').split(','):
oid = oid.strip()
if len(oid) > 1 and oid[0] in 'RNWrnw' and oid[1:].isdigit():
- places.append(napi.OsmID(oid[0].upper(), int(oid[1:])))
+ places.append(OsmID(oid[0].upper(), int(oid[1:])))
if len(places) > params.config().get_int('LOOKUP_MAX_COUNT'):
params.raise_error('Too many object IDs.')
if places:
results = await api.lookup(places, **details)
else:
- results = napi.SearchResults()
+ results = SearchResults()
if debug:
return params.build_response(loglib.get_and_disable(), num_results=len(results))
return params.build_response(output, num_results=len(results))
-async def _unstructured_search(query: str, api: napi.NominatimAPIAsync,
- details: Dict[str, Any]) -> napi.SearchResults:
+async def _unstructured_search(query: str, api: NominatimAPIAsync,
+ details: Dict[str, Any]) -> SearchResults:
if not query:
- return napi.SearchResults()
+ return SearchResults()
# Extract special format for coordinates from query.
query, x, y = helpers.extract_coords_from_query(query)
if x is not None:
assert y is not None
- details['near'] = napi.Point(x, y)
+ details['near'] = Point(x, y)
details['near_radius'] = 0.1
# If no query is left, revert to reverse search.
if x is not None and not query:
result = await api.reverse(details['near'], **details)
if not result:
- return napi.SearchResults()
+ return SearchResults()
- return napi.SearchResults(
- [napi.SearchResult(**{f.name: getattr(result, f.name)
- for f in dataclasses.fields(napi.SearchResult)
- if hasattr(result, f.name)})])
+ return SearchResults(
+ [SearchResult(**{f.name: getattr(result, f.name)
+ for f in dataclasses.fields(SearchResult)
+ if hasattr(result, f.name)})])
query, cls, typ = helpers.extract_category_from_query(query)
if cls is not None:
return await api.search(query, **details)
-async def search_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def search_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /search endpoint. See API docs for details.
"""
- fmt = params.parse_format(napi.SearchResults, 'jsonv2')
+ fmt = params.parse_format(SearchResults, 'jsonv2')
debug = params.setup_debugging()
details = params.parse_geometry_details(fmt)
details['min_rank'], details['max_rank'] = \
helpers.feature_type_to_rank(params.get('featureType', ''))
if params.get('featureType', None) is not None:
- details['layers'] = napi.DataLayer.ADDRESS
+ details['layers'] = DataLayer.ADDRESS
else:
details['layers'] = params.get_layers()
- details['locales'] = napi.Locales.from_accept_languages(params.get_accepted_languages())
+ details['locales'] = Locales.from_accept_languages(params.get_accepted_languages())
# unstructured query parameters
query = params.get('q', None)
return params.build_response(output, num_results=len(results))
-async def deletable_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def deletable_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /deletable endpoint.
This is a special endpoint that shows polygons that have been
deleted or are broken in the OSM data but are kept in the
return params.build_response(formatting.format_result(results, fmt, {}))
-async def polygons_endpoint(api: napi.NominatimAPIAsync, params: ASGIAdaptor) -> Any:
+async def polygons_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
""" Server glue for /polygons endpoint.
This is a special endpoint that shows polygons that have changed
their size but are kept in the Nominatim database with their
return params.build_response(formatting.format_result(results, fmt, {}))
-EndpointFunc = Callable[[napi.NominatimAPIAsync, ASGIAdaptor], Any]
+EndpointFunc = Callable[[NominatimAPIAsync, ASGIAdaptor], Any]
ROUTES = [
('status', status_endpoint),
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Version information for the Nominatim API.
+"""
+
+NOMINATIM_API_VERSION = '4.4.99'
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Command-line interface to the Nominatim functions for import, update,
import os
import sys
import argparse
+import asyncio
from pathlib import Path
-from nominatim.config import Configuration
-from nominatim.tools.exec_utils import run_php_server
-from nominatim.errors import UsageError
-from nominatim import clicmd
-from nominatim import version
-from nominatim.clicmd.args import NominatimArgs, Subcommand
+from .config import Configuration
+from .errors import UsageError
+from .tools.exec_utils import run_php_server
+from . import clicmd
+from . import version
+from .clicmd.args import NominatimArgs, Subcommand
LOG = logging.getLogger()
raise UsageError("PHP frontend not configured.")
run_php_server(args.server, args.project_dir / 'website')
else:
- import uvicorn # pylint: disable=import-outside-toplevel
- server_info = args.server.split(':', 1)
- host = server_info[0]
- if len(server_info) > 1:
- if not server_info[1].isdigit():
- raise UsageError('Invalid format for --server parameter. Use <host>:<port>')
- port = int(server_info[1])
- else:
- port = 8088
+ asyncio.run(self.run_uvicorn(args))
- server_module = importlib.import_module(f'nominatim.server.{args.engine}.server')
+ return 0
- app = server_module.get_application(args.project_dir)
- uvicorn.run(app, host=host, port=port)
- return 0
+ async def run_uvicorn(self, args: NominatimArgs) -> None:
+ import uvicorn # pylint: disable=import-outside-toplevel
+
+ server_info = args.server.split(':', 1)
+ host = server_info[0]
+ if len(server_info) > 1:
+ if not server_info[1].isdigit():
+ raise UsageError('Invalid format for --server parameter. Use <host>:<port>')
+ port = int(server_info[1])
+ else:
+ port = 8088
+
+ server_module = importlib.import_module(f'nominatim_api.server.{args.engine}.server')
+
+ app = server_module.get_application(args.project_dir)
+
+ config = uvicorn.Config(app, host=host, port=port)
+ server = uvicorn.Server(config)
+ await server.serve()
def get_set_parser() -> CommandlineParser:
parser.add_subcommand('admin', clicmd.AdminFuncs())
- parser.add_subcommand('export', clicmd.QueryExport())
- parser.add_subcommand('convert', clicmd.ConvertDB())
- parser.add_subcommand('serve', AdminServe())
+ try:
+ exportcmd = importlib.import_module('nominatim_db.clicmd.export')
+ apicmd = importlib.import_module('nominatim_db.clicmd.api')
+ convertcmd = importlib.import_module('nominatim_db.clicmd.convert')
+
+ parser.add_subcommand('export', exportcmd.QueryExport())
+ parser.add_subcommand('convert', convertcmd.ConvertDB())
+ parser.add_subcommand('serve', AdminServe())
+
+ parser.add_subcommand('search', apicmd.APISearch())
+ parser.add_subcommand('reverse', apicmd.APIReverse())
+ parser.add_subcommand('lookup', apicmd.APILookup())
+ parser.add_subcommand('details', apicmd.APIDetails())
+ parser.add_subcommand('status', apicmd.APIStatus())
+ except ModuleNotFoundError as ex:
+ if not ex.name or 'nominatim_api' not in ex.name: # pylint: disable=E1135
+ raise ex
+
+ parser.parser.epilog = \
+ '\n\nNominatim API package not found. The following commands are not available:'\
+ '\n export, convert, serve, search, reverse, lookup, details, status'\
+ "\n\nRun 'pip install nominatim-api' to install the package."
- parser.add_subcommand('search', clicmd.APISearch())
- parser.add_subcommand('reverse', clicmd.APIReverse())
- parser.add_subcommand('lookup', clicmd.APILookup())
- parser.add_subcommand('details', clicmd.APIDetails())
- parser.add_subcommand('status', clicmd.APIStatus())
return parser
--- /dev/null
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2023 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Subcommand definitions for the command-line tool.
+"""
+# mypy and pylint disagree about the style of explicit exports,
+# see https://github.com/PyCQA/pylint/issues/6006.
+# pylint: disable=useless-import-alias
+
+from .setup import SetupAll as SetupAll
+from .replication import UpdateReplication as UpdateReplication
+from .index import UpdateIndex as UpdateIndex
+from .refresh import UpdateRefresh as UpdateRefresh
+from .add_data import UpdateAddData as UpdateAddData
+from .admin import AdminFuncs as AdminFuncs
+from .freeze import SetupFreeze as SetupFreeze
+from .special_phrases import ImportSpecialPhrases as ImportSpecialPhrases
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'add-data' subcommand.
from typing import cast
import argparse
import logging
+import asyncio
import psutil
-from nominatim.clicmd.args import NominatimArgs
+from .args import NominatimArgs
+from ..db.connection import connect
+from ..tools.freeze import is_frozen
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
The command can also be used to add external non-OSM data to the
database. At the moment the only supported format is TIGER housenumber
data. See the online documentation at
- https://nominatim.org/release-docs/latest/admin/Import/#installing-tiger-housenumber-data-for-the-us
+ https://nominatim.org/release-docs/latest/customize/Tiger/
for more information.
"""
def run(self, args: NominatimArgs) -> int:
- from nominatim.tokenizer import factory as tokenizer_factory
- from nominatim.tools import tiger_data, add_osm_data
+ from ..tools import add_osm_data
+
+ with connect(args.config.get_libpq_dsn()) as conn:
+ if is_frozen(conn):
+ print('Database is marked frozen. New data can\'t be added.')
+ return 1
if args.tiger_data:
- tokenizer = tokenizer_factory.get_tokenizer_for_db(args.config)
- return tiger_data.add_tiger_data(args.tiger_data,
- args.config,
- args.threads or psutil.cpu_count() or 1,
- tokenizer)
+ return asyncio.run(self._add_tiger_data(args))
osm2pgsql_params = args.osm2pgsql_options(default_cache=1000, default_threads=1)
if args.file or args.diff:
osm2pgsql_params)
return 0
+
+
+ async def _add_tiger_data(self, args: NominatimArgs) -> int:
+ from ..tokenizer import factory as tokenizer_factory
+ from ..tools import tiger_data
+
+ assert args.tiger_data
+
+ tokenizer = tokenizer_factory.get_tokenizer_for_db(args.config)
+ return await tiger_data.add_tiger_data(args.tiger_data,
+ args.config,
+ args.threads or psutil.cpu_count() or 1,
+ tokenizer)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'admin' subcommand.
import argparse
import random
-from nominatim.db.connection import connect
-from nominatim.clicmd.args import NominatimArgs
-import nominatim.api as napi
+from ..errors import UsageError
+from ..db.connection import connect, table_exists
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
def _warm(self, args: NominatimArgs) -> int:
+ try:
+ import nominatim_api as napi
+ except ModuleNotFoundError as exp:
+ raise UsageError("Warming requires nominatim API. "
+ "Install with 'pip install nominatim-api'.") from exp
LOG.warning('Warming database caches')
api = napi.NominatimAPI(args.project_dir)
tokenizer = tokenizer_factory.get_tokenizer_for_db(args.config)
with connect(args.config.get_libpq_dsn()) as conn:
- if conn.table_exists('search_name'):
+ if table_exists(conn, 'search_name'):
words = tokenizer.most_frequent_words(conn, 1000)
else:
words = []
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Subcommand definitions for API calls from the command line.
"""
-from typing import Dict, Any
+from typing import Dict, Any, Optional
import argparse
import logging
import json
import sys
+from functools import reduce
-from nominatim.clicmd.args import NominatimArgs
-import nominatim.api as napi
-import nominatim.api.v1 as api_output
-from nominatim.api.v1.helpers import zoom_to_rank, deduplicate_results
-from nominatim.api.v1.format import dispatch as formatting
-import nominatim.api.logging as loglib
+import nominatim_api as napi
+import nominatim_api.v1 as api_output
+from nominatim_api.v1.helpers import zoom_to_rank, deduplicate_results
+from nominatim_api.v1.format import dispatch as formatting
+import nominatim_api.logging as loglib
+from ..errors import UsageError
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
"Parameter is difference tolerance in degrees."))
+def _get_geometry_output(args: NominatimArgs) -> napi.GeometryFormat:
+ """ Get the requested geometry output format in a API-compatible
+ format.
+ """
+ if not args.polygon_output:
+ return napi.GeometryFormat.NONE
+ if args.polygon_output == 'geojson':
+ return napi.GeometryFormat.GEOJSON
+ if args.polygon_output == 'kml':
+ return napi.GeometryFormat.KML
+ if args.polygon_output == 'svg':
+ return napi.GeometryFormat.SVG
+ if args.polygon_output == 'text':
+ return napi.GeometryFormat.TEXT
+
+ try:
+ return napi.GeometryFormat[args.polygon_output.upper()]
+ except KeyError as exp:
+ raise UsageError(f"Unknown polygon output format '{args.polygon_output}'.") from exp
+
+
+def _get_locales(args: NominatimArgs, default: Optional[str]) -> napi.Locales:
+ """ Get the locales from the language parameter.
+ """
+ if args.lang:
+ return napi.Locales.from_accept_languages(args.lang)
+ if default:
+ return napi.Locales.from_accept_languages(default)
+
+ return napi.Locales()
+
+
+def _get_layers(args: NominatimArgs, default: napi.DataLayer) -> Optional[napi.DataLayer]:
+ """ Get the list of selected layers as a DataLayer enum.
+ """
+ if not args.layers:
+ return default
+
+ return reduce(napi.DataLayer.__or__,
+ (napi.DataLayer[s.upper()] for s in args.layers))
+
+
class APISearch:
"""\
Execute a search query.
params: Dict[str, Any] = {'max_results': args.limit + min(args.limit, 10),
'address_details': True, # needed for display name
- 'geometry_output': args.get_geometry_output(),
+ 'geometry_output': _get_geometry_output(args),
'geometry_simplification': args.polygon_threshold,
'countries': args.countrycodes,
'excluded': args.exclude_place_ids,
'viewbox': args.viewbox,
'bounded_viewbox': args.bounded,
- 'locales': args.get_locales(api.config.DEFAULT_LANGUAGE)
+ 'locales': _get_locales(args, api.config.DEFAULT_LANGUAGE)
}
if args.query:
result = api.reverse(napi.Point(args.lon, args.lat),
max_rank=zoom_to_rank(args.zoom or 18),
- layers=args.get_layers(napi.DataLayer.ADDRESS | napi.DataLayer.POI),
+ layers=_get_layers(args, napi.DataLayer.ADDRESS | napi.DataLayer.POI),
address_details=True, # needed for display name
- geometry_output=args.get_geometry_output(),
+ geometry_output=_get_geometry_output(args),
geometry_simplification=args.polygon_threshold,
- locales=args.get_locales(api.config.DEFAULT_LANGUAGE))
+ locales=_get_locales(args, api.config.DEFAULT_LANGUAGE))
if args.format == 'debug':
print(loglib.get_and_disable())
results = api.lookup(places,
address_details=True, # needed for display name
- geometry_output=args.get_geometry_output(),
+ geometry_output=_get_geometry_output(args),
geometry_simplification=args.polygon_threshold or 0.0,
- locales=args.get_locales(api.config.DEFAULT_LANGUAGE))
+ locales=_get_locales(args, api.config.DEFAULT_LANGUAGE))
output = api_output.format_result(
results,
api = napi.NominatimAPI(args.project_dir)
- locales = args.get_locales(api.config.DEFAULT_LANGUAGE)
+ locales = _get_locales(args, api.config.DEFAULT_LANGUAGE)
result = api.details(place,
address_details=args.addressdetails,
linked_places=args.linkedplaces,
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Provides custom functions over command-line arguments.
from typing import Optional, List, Dict, Any, Sequence, Tuple
import argparse
import logging
-from functools import reduce
from pathlib import Path
-from nominatim.errors import UsageError
-from nominatim.config import Configuration
-from nominatim.typing import Protocol
-import nominatim.api as napi
+from ..errors import UsageError
+from ..config import Configuration
+from ..typing import Protocol
LOG = logging.getLogger()
raise UsageError('Cannot access file.')
return files
-
-
- def get_geometry_output(self) -> napi.GeometryFormat:
- """ Get the requested geometry output format in a API-compatible
- format.
- """
- if not self.polygon_output:
- return napi.GeometryFormat.NONE
- if self.polygon_output == 'geojson':
- return napi.GeometryFormat.GEOJSON
- if self.polygon_output == 'kml':
- return napi.GeometryFormat.KML
- if self.polygon_output == 'svg':
- return napi.GeometryFormat.SVG
- if self.polygon_output == 'text':
- return napi.GeometryFormat.TEXT
-
- try:
- return napi.GeometryFormat[self.polygon_output.upper()]
- except KeyError as exp:
- raise UsageError(f"Unknown polygon output format '{self.polygon_output}'.") from exp
-
-
- def get_locales(self, default: Optional[str]) -> napi.Locales:
- """ Get the locales from the language parameter.
- """
- if self.lang:
- return napi.Locales.from_accept_languages(self.lang)
- if default:
- return napi.Locales.from_accept_languages(default)
-
- return napi.Locales()
-
-
- def get_layers(self, default: napi.DataLayer) -> Optional[napi.DataLayer]:
- """ Get the list of selected layers as a DataLayer enum.
- """
- if not self.layers:
- return default
-
- return reduce(napi.DataLayer.__or__,
- (napi.DataLayer[s.upper()] for s in self.layers))
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'convert' subcommand.
import asyncio
from pathlib import Path
-from nominatim.clicmd.args import NominatimArgs
-from nominatim.errors import UsageError
+from ..errors import UsageError
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'export' subcommand.
import csv
import sys
-import sqlalchemy as sa
+import nominatim_api as napi
+from nominatim_api.results import create_from_placex_row, ReverseResult, add_result_details
+from nominatim_api.types import LookupDetails
-from nominatim.clicmd.args import NominatimArgs
-import nominatim.api as napi
-from nominatim.api.results import create_from_placex_row, ReverseResult, add_result_details
-from nominatim.api.types import LookupDetails
-from nominatim.errors import UsageError
+import sqlalchemy as sa # pylint: disable=C0411
+
+from ..errors import UsageError
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'freeze' subcommand.
"""
import argparse
-from nominatim.db.connection import connect
-from nominatim.clicmd.args import NominatimArgs
+from ..db.connection import connect
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'index' subcommand.
"""
import argparse
+import asyncio
import psutil
-from nominatim.db import status
-from nominatim.db.connection import connect
-from nominatim.clicmd.args import NominatimArgs
+from ..db import status
+from ..db.connection import connect
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
def run(self, args: NominatimArgs) -> int:
- from ..indexer.indexer import Indexer
- from ..tokenizer import factory as tokenizer_factory
-
- tokenizer = tokenizer_factory.get_tokenizer_for_db(args.config)
-
- indexer = Indexer(args.config.get_libpq_dsn(), tokenizer,
- args.threads or psutil.cpu_count() or 1)
-
- if not args.no_boundaries:
- indexer.index_boundaries(args.minrank, args.maxrank)
- if not args.boundaries_only:
- indexer.index_by_rank(args.minrank, args.maxrank)
- indexer.index_postcodes()
+ asyncio.run(self._do_index(args))
if not args.no_boundaries and not args.boundaries_only \
and args.minrank == 0 and args.maxrank == 30:
status.set_indexed(conn, True)
return 0
+
+
+ async def _do_index(self, args: NominatimArgs) -> None:
+ from ..tokenizer import factory as tokenizer_factory
+
+ tokenizer = tokenizer_factory.get_tokenizer_for_db(args.config)
+ from ..indexer.indexer import Indexer
+
+ indexer = Indexer(args.config.get_libpq_dsn(), tokenizer,
+ args.threads or psutil.cpu_count() or 1)
+
+ has_pending = True # run at least once
+ while has_pending:
+ if not args.no_boundaries:
+ await indexer.index_boundaries(args.minrank, args.maxrank)
+ if not args.boundaries_only:
+ await indexer.index_by_rank(args.minrank, args.maxrank)
+ await indexer.index_postcodes()
+ has_pending = indexer.has_pending()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of 'refresh' subcommand.
import argparse
import logging
from pathlib import Path
+import asyncio
-from nominatim.config import Configuration
-from nominatim.db.connection import connect
-from nominatim.tokenizer.base import AbstractTokenizer
-from nominatim.clicmd.args import NominatimArgs
+from ..config import Configuration
+from ..db.connection import connect, table_exists
+from ..tokenizer.base import AbstractTokenizer
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
args.project_dir, tokenizer)
indexer = Indexer(args.config.get_libpq_dsn(), tokenizer,
args.threads or 1)
- indexer.index_postcodes()
+ asyncio.run(indexer.index_postcodes())
else:
LOG.error("The place table doesn't exist. "
"Postcode updates on a frozen database is not possible.")
with connect(args.config.get_libpq_dsn()) as conn:
# If the table did not exist before, then the importance code
# needs to be enabled.
- if not conn.table_exists('secondary_importance'):
+ if not table_exists(conn, 'secondary_importance'):
args.functions = True
LOG.warning('Import secondary importance raster data from %s', args.project_dir)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'replication' sub-command.
import logging
import socket
import time
+import asyncio
-from nominatim.db import status
-from nominatim.db.connection import connect
-from nominatim.errors import UsageError
-from nominatim.clicmd.args import NominatimArgs
+from ..db import status
+from ..db.connection import connect
+from ..errors import UsageError
+from .args import NominatimArgs
LOG = logging.getLogger()
and update_interval < 86400:
LOG.fatal("Update interval too low for download.geofabrik.de.\n"
"Please check install documentation "
- "(https://nominatim.org/release-docs/latest/admin/Import-and-Update#"
+ "(https://nominatim.org/release-docs/latest/admin/Update/#"
"setting-up-the-update-process).")
raise UsageError("Invalid replication update interval setting.")
return update_interval
- def _update(self, args: NominatimArgs) -> None:
+ async def _update(self, args: NominatimArgs) -> None:
# pylint: disable=too-many-locals
from ..tools import replication
from ..indexer.indexer import Indexer
if state is not replication.UpdateState.NO_CHANGES and args.do_index:
index_start = dt.datetime.now(dt.timezone.utc)
- indexer.index_full(analyse=False)
+ await indexer.index_full(analyse=False)
with connect(dsn) as conn:
status.set_indexed(conn, True)
if state is replication.UpdateState.NO_CHANGES and \
args.catch_up or update_interval > 40*60:
- while indexer.has_pending():
- indexer.index_full(analyse=False)
+ await indexer.index_full(analyse=False)
if LOG.isEnabledFor(logging.WARNING):
assert batchdate is not None
if args.check_for_updates:
return self._check_for_updates(args)
- self._update(args)
+ asyncio.run(self._update(args))
return 0
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'import' subcommand.
import argparse
import logging
from pathlib import Path
+import asyncio
import psutil
-from nominatim.config import Configuration
-from nominatim.db.connection import connect
-from nominatim.db import status, properties
-from nominatim.tokenizer.base import AbstractTokenizer
-from nominatim.version import NOMINATIM_VERSION
-from nominatim.clicmd.args import NominatimArgs
-from nominatim.errors import UsageError
+from ..errors import UsageError
+from ..config import Configuration
+from ..db.connection import connect
+from ..db import status, properties
+from ..tokenizer.base import AbstractTokenizer
+from ..version import NOMINATIM_VERSION
+from .args import NominatimArgs
# Do not repeat documentation of subcommand classes.
# pylint: disable=C0111
def run(self, args: NominatimArgs) -> int: # pylint: disable=too-many-statements, too-many-branches
- from ..data import country_info
- from ..tools import database_import, refresh, postcodes, freeze
- from ..indexer.indexer import Indexer
-
- num_threads = args.threads or psutil.cpu_count() or 1
-
- country_info.setup_country_config(args.config)
-
if args.osm_file is None and args.continue_at is None and not args.prepare_database:
raise UsageError("No input files (use --osm-file).")
"Cannot use --continue and --prepare-database together."
)
+ return asyncio.run(self.async_run(args))
+
+
+ async def async_run(self, args: NominatimArgs) -> int:
+ from ..data import country_info
+ from ..tools import database_import, refresh, postcodes, freeze
+ from ..indexer.indexer import Indexer
+
+ num_threads = args.threads or psutil.cpu_count() or 1
+ country_info.setup_country_config(args.config)
if args.prepare_database or args.continue_at is None:
LOG.warning('Creating database')
return 0
if args.continue_at in (None, 'import-from-file'):
- files = args.get_osm_file_list()
- if not files:
- raise UsageError("No input files (use --osm-file).")
-
- if args.continue_at in ('import-from-file', None):
- # Check if the correct plugins are installed
- database_import.check_existing_database_plugins(args.config.get_libpq_dsn())
- LOG.warning('Setting up country tables')
- country_info.setup_country_tables(args.config.get_libpq_dsn(),
- args.config.lib_dir.data,
- args.no_partitions)
-
- LOG.warning('Importing OSM data file')
- database_import.import_osm_data(files,
- args.osm2pgsql_options(0, 1),
- drop=args.no_updates,
- ignore_errors=args.ignore_errors)
-
- LOG.warning('Importing wikipedia importance data')
- data_path = Path(args.config.WIKIPEDIA_DATA_PATH or args.project_dir)
- if refresh.import_wikipedia_articles(args.config.get_libpq_dsn(),
- data_path) > 0:
- LOG.error('Wikipedia importance dump file not found. '
- 'Calculating importance values of locations will not '
- 'use Wikipedia importance data.')
-
- LOG.warning('Importing secondary importance raster data')
- if refresh.import_secondary_importance(args.config.get_libpq_dsn(),
- args.project_dir) != 0:
- LOG.error('Secondary importance file not imported. '
- 'Falling back to default ranking.')
-
- self._setup_tables(args.config, args.reverse_only)
+ self._base_import(args)
if args.continue_at in ('import-from-file', 'load-data', None):
LOG.warning('Initialise tables')
database_import.truncate_data_tables(conn)
LOG.warning('Load data into placex table')
- database_import.load_data(args.config.get_libpq_dsn(), num_threads)
+ await database_import.load_data(args.config.get_libpq_dsn(), num_threads)
LOG.warning("Setting up tokenizer")
tokenizer = self._get_tokenizer(args.continue_at, args.config)
('import-from-file', 'load-data', 'indexing', None):
LOG.warning('Indexing places')
indexer = Indexer(args.config.get_libpq_dsn(), tokenizer, num_threads)
- indexer.index_full(analyse=not args.index_noanalyse)
+ await indexer.index_full(analyse=not args.index_noanalyse)
LOG.warning('Post-process tables')
with connect(args.config.get_libpq_dsn()) as conn:
- database_import.create_search_indices(conn, args.config,
- drop=args.no_updates,
- threads=num_threads)
+ await database_import.create_search_indices(conn, args.config,
+ drop=args.no_updates,
+ threads=num_threads)
LOG.warning('Create search index for default country names.')
country_info.create_country_names(conn, tokenizer,
args.config.get_str_list('LANGUAGES'))
return 0
+ def _base_import(self, args: NominatimArgs) -> None:
+ from ..tools import database_import, refresh
+ from ..data import country_info
+
+ files = args.get_osm_file_list()
+ if not files:
+ raise UsageError("No input files (use --osm-file).")
+
+ if args.continue_at in ('import-from-file', None):
+ # Check if the correct plugins are installed
+ database_import.check_existing_database_plugins(args.config.get_libpq_dsn())
+ LOG.warning('Setting up country tables')
+ country_info.setup_country_tables(args.config.get_libpq_dsn(),
+ args.config.lib_dir.data,
+ args.no_partitions)
+
+ LOG.warning('Importing OSM data file')
+ database_import.import_osm_data(files,
+ args.osm2pgsql_options(0, 1),
+ drop=args.no_updates,
+ ignore_errors=args.ignore_errors)
+
+ LOG.warning('Importing wikipedia importance data')
+ data_path = Path(args.config.WIKIPEDIA_DATA_PATH or args.project_dir)
+ if refresh.import_wikipedia_articles(args.config.get_libpq_dsn(),
+ data_path) > 0:
+ LOG.error('Wikipedia importance dump file not found. '
+ 'Calculating importance values of locations will not '
+ 'use Wikipedia importance data.')
+
+ LOG.warning('Importing secondary importance raster data')
+ if refresh.import_secondary_importance(args.config.get_libpq_dsn(),
+ args.project_dir) != 0:
+ LOG.error('Secondary importance file not imported. '
+ 'Falling back to default ranking.')
+
+ self._setup_tables(args.config, args.reverse_only)
+
+
def _setup_tables(self, config: Configuration, reverse_only: bool) -> None:
""" Set up the basic database layout: tables, indexes and functions.
"""
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Implementation of the 'special-phrases' command.
import logging
from pathlib import Path
-from nominatim.errors import UsageError
-from nominatim.db.connection import connect
-from nominatim.tools.special_phrases.sp_importer import SPImporter, SpecialPhraseLoader
-from nominatim.tools.special_phrases.sp_wiki_loader import SPWikiLoader
-from nominatim.tools.special_phrases.sp_csv_loader import SPCsvLoader
-from nominatim.clicmd.args import NominatimArgs
+from ..errors import UsageError
+from ..db.connection import connect
+from ..tools.special_phrases.sp_importer import SPImporter, SpecialPhraseLoader
+from ..tools.special_phrases.sp_wiki_loader import SPWikiLoader
+from ..tools.special_phrases.sp_csv_loader import SPCsvLoader
+from .args import NominatimArgs
LOG = logging.getLogger()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Nominatim configuration accessor.
"""
-from typing import Dict, Any, List, Mapping, Optional
+from typing import Union, Dict, Any, List, Mapping, Optional
import importlib.util
import logging
import os
import yaml
from dotenv import dotenv_values
-from psycopg2.extensions import parse_dsn
-from nominatim.typing import StrPath
-from nominatim.errors import UsageError
-import nominatim.paths
+from psycopg.conninfo import conninfo_to_dict
+
+from .typing import StrPath
+from .errors import UsageError
+from . import paths
LOG = logging.getLogger()
CONFIG_CACHE : Dict[str, Any] = {}
environ: Optional[Mapping[str, str]] = None) -> None:
self.environ = environ or os.environ
self.project_dir = project_dir
- self.config_dir = nominatim.paths.CONFIG_DIR
+ self.config_dir = paths.CONFIG_DIR
self._config = dotenv_values(str(self.config_dir / 'env.defaults'))
if self.project_dir is not None and (self.project_dir / '.env').is_file():
self.project_dir = self.project_dir.resolve()
class _LibDirs:
module: Path
osm2pgsql: Path
- php = nominatim.paths.PHPLIB_DIR
- sql = nominatim.paths.SQLLIB_DIR
- data = nominatim.paths.DATA_DIR
+ php = paths.PHPLIB_DIR
+ sql = paths.SQLLIB_DIR
+ data = paths.DATA_DIR
self.lib_dir = _LibDirs()
self._private_plugins: Dict[str, object] = {}
""" Set paths to library functions and data.
"""
for key, value in kwargs.items():
- setattr(self.lib_dir, key, Path(value))
+ setattr(self.lib_dir, key, None if value is None else Path(value))
def __getattr__(self, name: str) -> str:
return dsn
- def get_database_params(self) -> Mapping[str, str]:
+ def get_database_params(self) -> Mapping[str, Union[str, int, None]]:
""" Get the configured parameters for the database connection
as a mapping.
"""
if dsn.startswith('pgsql:'):
return dict((p.split('=', 1) for p in dsn[6:].split(';')))
- return parse_dsn(dsn)
+ return conninfo_to_dict(dsn)
def get_import_style_file(self) -> Path:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for importing and managing static country information.
"""
from typing import Dict, Any, Iterable, Tuple, Optional, Container, overload
from pathlib import Path
-import psycopg2.extras
-from nominatim.db import utils as db_utils
-from nominatim.db.connection import connect, Connection
-from nominatim.errors import UsageError
-from nominatim.config import Configuration
-from nominatim.tokenizer.base import AbstractTokenizer
+from ..db import utils as db_utils
+from ..db.connection import connect, Connection, register_hstore
+from ..errors import UsageError
+from ..config import Configuration
+from ..tokenizer.base import AbstractTokenizer
def _flatten_name_list(names: Any) -> Dict[str, str]:
if names is None:
params.append((ccode, props['names'], lang, partition))
with connect(dsn) as conn:
+ register_hstore(conn)
with conn.cursor() as cur:
- psycopg2.extras.register_hstore(cur)
cur.execute(
""" CREATE TABLE public.country_name (
country_code character varying(2),
country_default_language_code text,
partition integer
); """)
- cur.execute_values(
+ cur.executemany(
""" INSERT INTO public.country_name
- (country_code, name, country_default_language_code, partition) VALUES %s
+ (country_code, name, country_default_language_code, partition)
+ VALUES (%s, %s, %s, %s)
""", params)
conn.commit()
return ':' not in key or not languages or \
key[key.index(':') + 1:] in languages
+ register_hstore(conn)
with conn.cursor() as cur:
- psycopg2.extras.register_hstore(cur)
cur.execute("""SELECT country_code, name FROM country_name
WHERE country_code is not null""")
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Wrapper around place information the indexer gets from the database and hands to
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Data class for a single name of a place.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for formatting postcodes according to their country-specific
from typing import Any, Mapping, Optional, Set, Match
import re
-from nominatim.errors import UsageError
-from nominatim.data import country_info
+from ..errors import UsageError
+from . import country_info
class CountryPostcodeMatcher:
""" Matches and formats a postcode according to a format definition
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Specialised connection and cursor functions.
+"""
+from typing import Optional, Any, Dict, Tuple
+import logging
+import os
+
+import psycopg
+import psycopg.types.hstore
+from psycopg import sql as pysql
+
+from ..typing import SysEnv
+from ..errors import UsageError
+
+LOG = logging.getLogger()
+
+Cursor = psycopg.Cursor[Any]
+Connection = psycopg.Connection[Any]
+
+def execute_scalar(conn: Connection, sql: psycopg.abc.Query, args: Any = None) -> Any:
+ """ Execute query that returns a single value. The value is returned.
+ If the query yields more than one row, a ValueError is raised.
+ """
+ with conn.cursor(row_factory=psycopg.rows.tuple_row) as cur:
+ cur.execute(sql, args)
+
+ if cur.rowcount != 1:
+ raise RuntimeError("Query did not return a single row.")
+
+ result = cur.fetchone()
+
+ assert result is not None
+ return result[0]
+
+
+def table_exists(conn: Connection, table: str) -> bool:
+ """ Check that a table with the given name exists in the database.
+ """
+ num = execute_scalar(conn,
+ """SELECT count(*) FROM pg_tables
+ WHERE tablename = %s and schemaname = 'public'""", (table, ))
+ return num == 1 if isinstance(num, int) else False
+
+
+def table_has_column(conn: Connection, table: str, column: str) -> bool:
+ """ Check if the table 'table' exists and has a column with name 'column'.
+ """
+ has_column = execute_scalar(conn,
+ """SELECT count(*) FROM information_schema.columns
+ WHERE table_name = %s and column_name = %s""",
+ (table, column))
+ return has_column > 0 if isinstance(has_column, int) else False
+
+
+def index_exists(conn: Connection, index: str, table: Optional[str] = None) -> bool:
+ """ Check that an index with the given name exists in the database.
+ If table is not None then the index must relate to the given
+ table.
+ """
+ with conn.cursor() as cur:
+ cur.execute("""SELECT tablename FROM pg_indexes
+ WHERE indexname = %s and schemaname = 'public'""", (index, ))
+ if cur.rowcount == 0:
+ return False
+
+ if table is not None:
+ row = cur.fetchone()
+ if row is None or not isinstance(row[0], str):
+ return False
+ return row[0] == table
+
+ return True
+
+def drop_tables(conn: Connection, *names: str,
+ if_exists: bool = True, cascade: bool = False) -> None:
+ """ Drop one or more tables with the given names.
+ Set `if_exists` to False if a non-existent table should raise
+ an exception instead of just being ignored. `cascade` will cause
+ depended objects to be dropped as well.
+ The caller needs to take care of committing the change.
+ """
+ sql = pysql.SQL('DROP TABLE%s{}%s' % (
+ ' IF EXISTS ' if if_exists else ' ',
+ ' CASCADE' if cascade else ''))
+
+ with conn.cursor() as cur:
+ for name in names:
+ cur.execute(sql.format(pysql.Identifier(name)))
+
+
+def server_version_tuple(conn: Connection) -> Tuple[int, int]:
+ """ Return the server version as a tuple of (major, minor).
+ Converts correctly for pre-10 and post-10 PostgreSQL versions.
+ """
+ version = conn.info.server_version
+ if version < 100000:
+ return (int(version / 10000), int((version % 10000) / 100))
+
+ return (int(version / 10000), version % 10000)
+
+
+def postgis_version_tuple(conn: Connection) -> Tuple[int, int]:
+ """ Return the postgis version installed in the database as a
+ tuple of (major, minor). Assumes that the PostGIS extension
+ has been installed already.
+ """
+ version = execute_scalar(conn, 'SELECT postgis_lib_version()')
+
+ version_parts = version.split('.')
+ if len(version_parts) < 2:
+ raise UsageError(f"Error fetching Postgis version. Bad format: {version}")
+
+ return (int(version_parts[0]), int(version_parts[1]))
+
+
+def register_hstore(conn: Connection) -> None:
+ """ Register the hstore type with psycopg for the connection.
+ """
+ info = psycopg.types.TypeInfo.fetch(conn, "hstore")
+ if info is None:
+ raise RuntimeError('Hstore extension is requested but not installed.')
+ psycopg.types.hstore.register_hstore(info, conn)
+
+
+def connect(dsn: str, **kwargs: Any) -> Connection:
+ """ Open a connection to the database using the specialised connection
+ factory. The returned object may be used in conjunction with 'with'.
+ When used outside a context manager, use the `connection` attribute
+ to get the connection.
+ """
+ try:
+ return psycopg.connect(dsn, row_factory=psycopg.rows.namedtuple_row, **kwargs)
+ except psycopg.OperationalError as err:
+ raise UsageError(f"Cannot connect to database: {err}") from err
+
+
+# Translation from PG connection string parameters to PG environment variables.
+# Derived from https://www.postgresql.org/docs/current/libpq-envars.html.
+_PG_CONNECTION_STRINGS = {
+ 'host': 'PGHOST',
+ 'hostaddr': 'PGHOSTADDR',
+ 'port': 'PGPORT',
+ 'dbname': 'PGDATABASE',
+ 'user': 'PGUSER',
+ 'password': 'PGPASSWORD',
+ 'passfile': 'PGPASSFILE',
+ 'channel_binding': 'PGCHANNELBINDING',
+ 'service': 'PGSERVICE',
+ 'options': 'PGOPTIONS',
+ 'application_name': 'PGAPPNAME',
+ 'sslmode': 'PGSSLMODE',
+ 'requiressl': 'PGREQUIRESSL',
+ 'sslcompression': 'PGSSLCOMPRESSION',
+ 'sslcert': 'PGSSLCERT',
+ 'sslkey': 'PGSSLKEY',
+ 'sslrootcert': 'PGSSLROOTCERT',
+ 'sslcrl': 'PGSSLCRL',
+ 'requirepeer': 'PGREQUIREPEER',
+ 'ssl_min_protocol_version': 'PGSSLMINPROTOCOLVERSION',
+ 'ssl_max_protocol_version': 'PGSSLMAXPROTOCOLVERSION',
+ 'gssencmode': 'PGGSSENCMODE',
+ 'krbsrvname': 'PGKRBSRVNAME',
+ 'gsslib': 'PGGSSLIB',
+ 'connect_timeout': 'PGCONNECT_TIMEOUT',
+ 'target_session_attrs': 'PGTARGETSESSIONATTRS',
+}
+
+
+def get_pg_env(dsn: str,
+ base_env: Optional[SysEnv] = None) -> Dict[str, str]:
+ """ Return a copy of `base_env` with the environment variables for
+ PostgreSQL set up from the given database connection string.
+ If `base_env` is None, then the OS environment is used as a base
+ environment.
+ """
+ env = dict(base_env if base_env is not None else os.environ)
+
+ for param, value in psycopg.conninfo.conninfo_to_dict(dsn).items():
+ if param in _PG_CONNECTION_STRINGS:
+ env[_PG_CONNECTION_STRINGS[param]] = str(value)
+ else:
+ LOG.error("Unknown connection parameter '%s' ignored.", param)
+
+ return env
+
+
+async def run_async_query(dsn: str, query: psycopg.abc.Query) -> None:
+ """ Open a connection to the database and run a single query
+ asynchronously.
+ """
+ async with await psycopg.AsyncConnection.connect(dsn) as aconn:
+ await aconn.execute(query)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Query and access functions for the in-database property table.
"""
from typing import Optional, cast
-from nominatim.db.connection import Connection
+from .connection import Connection, table_exists
def set_property(conn: Connection, name: str, value: str) -> None:
""" Add or replace the property with the given name.
""" Return the current value of the given property or None if the property
is not set.
"""
- if not conn.table_exists('nominatim_properties'):
+ if not table_exists(conn, 'nominatim_properties'):
return None
with conn.cursor() as cur:
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+A connection pool that executes incoming queries in parallel.
+"""
+from typing import Any, Tuple, Optional
+import asyncio
+import logging
+import time
+
+import psycopg
+
+LOG = logging.getLogger()
+
+QueueItem = Optional[Tuple[psycopg.abc.Query, Any]]
+
+class QueryPool:
+ """ Pool to run SQL queries in parallel asynchronous execution.
+
+ All queries are run in autocommit mode. If parallel execution leads
+ to a deadlock, then the query is repeated.
+ The results of the queries is discarded.
+ """
+ def __init__(self, dsn: str, pool_size: int = 1, **conn_args: Any) -> None:
+ self.wait_time = 0.0
+ self.query_queue: 'asyncio.Queue[QueueItem]' = asyncio.Queue(maxsize=2 * pool_size)
+
+ self.pool = [asyncio.create_task(self._worker_loop(dsn, **conn_args))
+ for _ in range(pool_size)]
+
+
+ async def put_query(self, query: psycopg.abc.Query, params: Any) -> None:
+ """ Schedule a query for execution.
+ """
+ tstart = time.time()
+ await self.query_queue.put((query, params))
+ self.wait_time += time.time() - tstart
+ await asyncio.sleep(0)
+
+
+ async def finish(self) -> None:
+ """ Wait for all queries to finish and close the pool.
+ """
+ for _ in self.pool:
+ await self.query_queue.put(None)
+
+ tstart = time.time()
+ await asyncio.wait(self.pool)
+ self.wait_time += time.time() - tstart
+
+ for task in self.pool:
+ excp = task.exception()
+ if excp is not None:
+ raise excp
+
+
+ async def _worker_loop(self, dsn: str, **conn_args: Any) -> None:
+ conn_args['autocommit'] = True
+ aconn = await psycopg.AsyncConnection.connect(dsn, **conn_args)
+ async with aconn:
+ async with aconn.cursor() as cur:
+ item = await self.query_queue.get()
+ while item is not None:
+ try:
+ if item[1] is None:
+ await cur.execute(item[0])
+ else:
+ await cur.execute(item[0], item[1])
+
+ item = await self.query_queue.get()
+ except psycopg.errors.DeadlockDetected:
+ assert item is not None
+ LOG.info("Deadlock detected (sql = %s, params = %s), retry.",
+ str(item[0]), str(item[1]))
+ # item is still valid here, causing a retry
+
+
+ async def __aenter__(self) -> 'QueryPool':
+ return self
+
+
+ async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
+ await self.finish()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Preprocessing of SQL files.
"""
from typing import Set, Dict, Any, cast
+
import jinja2
-from nominatim.db.connection import Connection
-from nominatim.db.async_connection import WorkerPool
-from nominatim.config import Configuration
+from .connection import Connection, server_version_tuple, postgis_version_tuple
+from ..config import Configuration
+from ..db.query_pool import QueryPool
def _get_partitions(conn: Connection) -> Set[int]:
""" Get the set of partitions currently in use.
""" Set up a dictionary with various optional Postgresql/Postgis features that
depend on the database version.
"""
- pg_version = conn.server_version_tuple()
- postgis_version = conn.postgis_version_tuple()
+ pg_version = server_version_tuple(conn)
+ postgis_version = postgis_version_tuple(conn)
pg11plus = pg_version >= (11, 0, 0)
ps3 = postgis_version >= (3, 0)
return {
conn.commit()
- def run_parallel_sql_file(self, dsn: str, name: str, num_threads: int = 1,
- **kwargs: Any) -> None:
+ async def run_parallel_sql_file(self, dsn: str, name: str, num_threads: int = 1,
+ **kwargs: Any) -> None:
""" Execute the given SQL files using parallel asynchronous connections.
The keyword arguments may supply additional parameters for
preprocessing.
parts = sql.split('\n---\n')
- with WorkerPool(dsn, num_threads) as pool:
+ async with QueryPool(dsn, num_threads) as pool:
for part in parts:
- pool.next_free_worker().perform(part)
+ await pool.put_query(part, None)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Access and helper functions for the status and status log table.
"""
-from typing import Optional, Tuple, cast
+from typing import Optional, Tuple
import datetime as dt
import logging
import re
-from nominatim.db.connection import Connection
-from nominatim.tools.exec_utils import get_url
-from nominatim.errors import UsageError
-from nominatim.typing import TypedDict
+from .connection import Connection, table_exists, execute_scalar
+from ..utils.url_utils import get_url
+from ..errors import UsageError
LOG = logging.getLogger()
ISODATE_FORMAT = '%Y-%m-%dT%H:%M:%S'
-class StatusRow(TypedDict):
- """ Dictionary of columns of the import_status table.
- """
- lastimportdate: dt.datetime
- sequence_id: Optional[int]
- indexed: Optional[bool]
-
-
def compute_database_date(conn: Connection, offline: bool = False) -> dt.datetime:
""" Determine the date of the database from the newest object in the
data base.
"""
# If there is a date from osm2pgsql available, use that.
- if conn.table_exists('osm2pgsql_properties'):
+ if table_exists(conn, 'osm2pgsql_properties'):
with conn.cursor() as cur:
cur.execute(""" SELECT value FROM osm2pgsql_properties
WHERE property = 'current_timestamp' """)
raise UsageError("Cannot determine database date from data in offline mode.")
# Else, find the node with the highest ID in the database
- with conn.cursor() as cur:
- if conn.table_exists('place'):
- osmid = cur.scalar("SELECT max(osm_id) FROM place WHERE osm_type='N'")
- else:
- osmid = cur.scalar("SELECT max(osm_id) FROM placex WHERE osm_type='N'")
+ if table_exists(conn, 'place'):
+ osmid = execute_scalar(conn, "SELECT max(osm_id) FROM place WHERE osm_type='N'")
+ else:
+ osmid = execute_scalar(conn, "SELECT max(osm_id) FROM placex WHERE osm_type='N'")
- if osmid is None:
- LOG.fatal("No data found in the database.")
- raise UsageError("No data found in the database.")
+ if osmid is None:
+ LOG.fatal("No data found in the database.")
+ raise UsageError("No data found in the database.")
LOG.info("Using node id %d for timestamp lookup", osmid)
# Get the node from the API to find the timestamp when it was created.
if cur.rowcount < 1:
return None, None, None
- row = cast(StatusRow, cur.fetchone())
- return row['lastimportdate'], row['sequence_id'], row['indexed']
+ row = cur.fetchone()
+ assert row
+ return row.lastimportdate, row.sequence_id, row.indexed
def set_indexed(conn: Connection, state: bool) -> None:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper functions for handling DB accesses.
"""
-from typing import IO, Optional, Union, Any, Iterable
+from typing import IO, Optional, Union
import subprocess
import logging
import gzip
-import io
from pathlib import Path
-from nominatim.db.connection import get_pg_env, Cursor
-from nominatim.errors import UsageError
+from .connection import get_pg_env
+from ..errors import UsageError
LOG = logging.getLogger()
if ret != 0 or remain > 0:
raise UsageError("Failed to execute SQL file.")
-
-
-# List of characters that need to be quoted for the copy command.
-_SQL_TRANSLATION = {ord('\\'): '\\\\',
- ord('\t'): '\\t',
- ord('\n'): '\\n'}
-
-
-class CopyBuffer:
- """ Data collector for the copy_from command.
- """
-
- def __init__(self) -> None:
- self.buffer = io.StringIO()
-
-
- def __enter__(self) -> 'CopyBuffer':
- return self
-
-
- def size(self) -> int:
- """ Return the number of bytes the buffer currently contains.
- """
- return self.buffer.tell()
-
- def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
- if self.buffer is not None:
- self.buffer.close()
-
-
- def add(self, *data: Any) -> None:
- """ Add another row of data to the copy buffer.
- """
- first = True
- for column in data:
- if first:
- first = False
- else:
- self.buffer.write('\t')
- if column is None:
- self.buffer.write('\\N')
- else:
- self.buffer.write(str(column).translate(_SQL_TRANSLATION))
- self.buffer.write('\n')
-
-
- def copy_out(self, cur: Cursor, table: str, columns: Optional[Iterable[str]] = None) -> None:
- """ Copy all collected data into the given table.
-
- The buffer is empty and reusable after this operation.
- """
- if self.buffer.tell() > 0:
- self.buffer.seek(0)
- cur.copy_from(self.buffer, table, columns=columns)
- self.buffer = io.StringIO()
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Custom exception and error classes for Nominatim.
+"""
+
+class UsageError(Exception):
+ """ An error raised because of bad user input. This error will usually
+ not cause a stack trace to be printed unless debugging is enabled.
+ """
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Main work horse for indexing (computing addresses) the database.
+"""
+from typing import cast, List, Any
+import logging
+import time
+
+import psycopg
+
+from ..db.connection import connect, execute_scalar
+from ..db.query_pool import QueryPool
+from ..tokenizer.base import AbstractTokenizer
+from .progress import ProgressLogger
+from . import runners
+
+LOG = logging.getLogger()
+
+class Indexer:
+ """ Main indexing routine.
+ """
+
+ def __init__(self, dsn: str, tokenizer: AbstractTokenizer, num_threads: int):
+ self.dsn = dsn
+ self.tokenizer = tokenizer
+ self.num_threads = num_threads
+
+
+ def has_pending(self) -> bool:
+ """ Check if any data still needs indexing.
+ This function must only be used after the import has finished.
+ Otherwise it will be very expensive.
+ """
+ with connect(self.dsn) as conn:
+ with conn.cursor() as cur:
+ cur.execute("SELECT 'a' FROM placex WHERE indexed_status > 0 LIMIT 1")
+ return cur.rowcount > 0
+
+
+ async def index_full(self, analyse: bool = True) -> None:
+ """ Index the complete database. This will first index boundaries
+ followed by all other objects. When `analyse` is True, then the
+ database will be analysed at the appropriate places to
+ ensure that database statistics are updated.
+ """
+ with connect(self.dsn) as conn:
+ conn.autocommit = True
+
+ def _analyze() -> None:
+ if analyse:
+ with conn.cursor() as cur:
+ cur.execute('ANALYZE')
+
+ while True:
+ if await self.index_by_rank(0, 4) > 0:
+ _analyze()
+
+ if await self.index_boundaries(0, 30) > 100:
+ _analyze()
+
+ if await self.index_by_rank(5, 25) > 100:
+ _analyze()
+
+ if await self.index_by_rank(26, 30) > 1000:
+ _analyze()
+
+ if await self.index_postcodes() > 100:
+ _analyze()
+
+ if not self.has_pending():
+ break
+
+
+ async def index_boundaries(self, minrank: int, maxrank: int) -> int:
+ """ Index only administrative boundaries within the given rank range.
+ """
+ total = 0
+ LOG.warning("Starting indexing boundaries using %s threads",
+ self.num_threads)
+
+ with self.tokenizer.name_analyzer() as analyzer:
+ for rank in range(max(minrank, 4), min(maxrank, 26)):
+ total += await self._index(runners.BoundaryRunner(rank, analyzer))
+
+ return total
+
+ async def index_by_rank(self, minrank: int, maxrank: int) -> int:
+ """ Index all entries of placex in the given rank range (inclusive)
+ in order of their address rank.
+
+ When rank 30 is requested then also interpolations and
+ places with address rank 0 will be indexed.
+ """
+ total = 0
+ maxrank = min(maxrank, 30)
+ LOG.warning("Starting indexing rank (%i to %i) using %i threads",
+ minrank, maxrank, self.num_threads)
+
+ with self.tokenizer.name_analyzer() as analyzer:
+ for rank in range(max(1, minrank), maxrank + 1):
+ if rank >= 30:
+ batch = 20
+ elif rank >= 26:
+ batch = 5
+ else:
+ batch = 1
+ total += await self._index(runners.RankRunner(rank, analyzer), batch)
+
+ if maxrank == 30:
+ total += await self._index(runners.RankRunner(0, analyzer))
+ total += await self._index(runners.InterpolationRunner(analyzer), 20)
+
+ return total
+
+
+ async def index_postcodes(self) -> int:
+ """Index the entries of the location_postcode table.
+ """
+ LOG.warning("Starting indexing postcodes using %s threads", self.num_threads)
+
+ return await self._index(runners.PostcodeRunner(), 20)
+
+
+ def update_status_table(self) -> None:
+ """ Update the status in the status table to 'indexed'.
+ """
+ with connect(self.dsn) as conn:
+ with conn.cursor() as cur:
+ cur.execute('UPDATE import_status SET indexed = true')
+
+ conn.commit()
+
+ async def _index(self, runner: runners.Runner, batch: int = 1) -> int:
+ """ Index a single rank or table. `runner` describes the SQL to use
+ for indexing. `batch` describes the number of objects that
+ should be processed with a single SQL statement
+ """
+ LOG.warning("Starting %s (using batch size %s)", runner.name(), batch)
+
+ total_tuples = self._prepare_indexing(runner)
+
+ progress = ProgressLogger(runner.name(), total_tuples)
+
+ if total_tuples > 0:
+ async with await psycopg.AsyncConnection.connect(
+ self.dsn, row_factory=psycopg.rows.dict_row) as aconn,\
+ QueryPool(self.dsn, self.num_threads, autocommit=True) as pool:
+ fetcher_time = 0.0
+ tstart = time.time()
+ async with aconn.cursor(name='places') as cur:
+ query = runner.index_places_query(batch)
+ params: List[Any] = []
+ num_places = 0
+ async for place in cur.stream(runner.sql_get_objects()):
+ fetcher_time += time.time() - tstart
+
+ params.extend(runner.index_places_params(place))
+ num_places += 1
+
+ if num_places >= batch:
+ LOG.debug("Processing places: %s", str(params))
+ await pool.put_query(query, params)
+ progress.add(num_places)
+ params = []
+ num_places = 0
+
+ tstart = time.time()
+
+ if num_places > 0:
+ await pool.put_query(runner.index_places_query(num_places), params)
+
+ LOG.info("Wait time: fetcher: %.2fs, pool: %.2fs",
+ fetcher_time, pool.wait_time)
+
+ return progress.done()
+
+
+ def _prepare_indexing(self, runner: runners.Runner) -> int:
+ with connect(self.dsn) as conn:
+ hstore_info = psycopg.types.TypeInfo.fetch(conn, "hstore")
+ if hstore_info is None:
+ raise RuntimeError('Hstore extension is requested but not installed.')
+ psycopg.types.hstore.register_hstore(hstore_info)
+
+ total_tuples = execute_scalar(conn, runner.sql_count_objects())
+ LOG.debug("Total number of rows: %i", total_tuples)
+ return cast(int, total_tuples)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helpers for progress logging.
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Mix-ins that provide the actual commands for the indexer for various indexing
+tasks.
+"""
+from typing import Any, Sequence
+
+from psycopg import sql as pysql
+from psycopg.abc import Query
+from psycopg.rows import DictRow
+from psycopg.types.json import Json
+
+from ..typing import Protocol
+from ..data.place_info import PlaceInfo
+from ..tokenizer.base import AbstractAnalyzer
+
+# pylint: disable=C0111
+
+def _mk_valuelist(template: str, num: int) -> pysql.Composed:
+ return pysql.SQL(',').join([pysql.SQL(template)] * num)
+
+def _analyze_place(place: DictRow, analyzer: AbstractAnalyzer) -> Json:
+ return Json(analyzer.process_place(PlaceInfo(place)))
+
+
+class Runner(Protocol):
+ def name(self) -> str: ...
+ def sql_count_objects(self) -> Query: ...
+ def sql_get_objects(self) -> Query: ...
+ def index_places_query(self, batch_size: int) -> Query: ...
+ def index_places_params(self, place: DictRow) -> Sequence[Any]: ...
+
+
+SELECT_SQL = pysql.SQL("""SELECT place_id, extra.*
+ FROM (SELECT * FROM placex {}) as px,
+ LATERAL placex_indexing_prepare(px) as extra """)
+UPDATE_LINE = "(%s, %s::hstore, %s::hstore, %s::int, %s::jsonb)"
+
+class AbstractPlacexRunner:
+ """ Returns SQL commands for indexing of the placex table.
+ """
+
+ def __init__(self, rank: int, analyzer: AbstractAnalyzer) -> None:
+ self.rank = rank
+ self.analyzer = analyzer
+
+
+ def index_places_query(self, batch_size: int) -> Query:
+ return pysql.SQL(
+ """ UPDATE placex
+ SET indexed_status = 0, address = v.addr, token_info = v.ti,
+ name = v.name, linked_place_id = v.linked_place_id
+ FROM (VALUES {}) as v(id, name, addr, linked_place_id, ti)
+ WHERE place_id = v.id
+ """).format(_mk_valuelist(UPDATE_LINE, batch_size))
+
+
+ def index_places_params(self, place: DictRow) -> Sequence[Any]:
+ return (place['place_id'],
+ place['name'],
+ place['address'],
+ place['linked_place_id'],
+ _analyze_place(place, self.analyzer))
+
+
+class RankRunner(AbstractPlacexRunner):
+ """ Returns SQL commands for indexing one rank within the placex table.
+ """
+
+ def name(self) -> str:
+ return f"rank {self.rank}"
+
+ def sql_count_objects(self) -> pysql.Composed:
+ return pysql.SQL("""SELECT count(*) FROM placex
+ WHERE rank_address = {} and indexed_status > 0
+ """).format(pysql.Literal(self.rank))
+
+ def sql_get_objects(self) -> pysql.Composed:
+ return SELECT_SQL.format(pysql.SQL(
+ """WHERE placex.indexed_status > 0 and placex.rank_address = {}
+ ORDER BY placex.geometry_sector
+ """).format(pysql.Literal(self.rank)))
+
+
+class BoundaryRunner(AbstractPlacexRunner):
+ """ Returns SQL commands for indexing the administrative boundaries
+ of a certain rank.
+ """
+
+ def name(self) -> str:
+ return f"boundaries rank {self.rank}"
+
+ def sql_count_objects(self) -> Query:
+ return pysql.SQL("""SELECT count(*) FROM placex
+ WHERE indexed_status > 0
+ AND rank_search = {}
+ AND class = 'boundary' and type = 'administrative'
+ """).format(pysql.Literal(self.rank))
+
+ def sql_get_objects(self) -> Query:
+ return SELECT_SQL.format(pysql.SQL(
+ """WHERE placex.indexed_status > 0 and placex.rank_search = {}
+ and placex.class = 'boundary' and placex.type = 'administrative'
+ ORDER BY placex.partition, placex.admin_level
+ """).format(pysql.Literal(self.rank)))
+
+
+class InterpolationRunner:
+ """ Returns SQL commands for indexing the address interpolation table
+ location_property_osmline.
+ """
+
+ def __init__(self, analyzer: AbstractAnalyzer) -> None:
+ self.analyzer = analyzer
+
+
+ def name(self) -> str:
+ return "interpolation lines (location_property_osmline)"
+
+ def sql_count_objects(self) -> Query:
+ return """SELECT count(*) FROM location_property_osmline
+ WHERE indexed_status > 0"""
+
+
+ def sql_get_objects(self) -> Query:
+ return """SELECT place_id, get_interpolation_address(address, osm_id) as address
+ FROM location_property_osmline
+ WHERE indexed_status > 0
+ ORDER BY geometry_sector"""
+
+
+ def index_places_query(self, batch_size: int) -> Query:
+ return pysql.SQL("""UPDATE location_property_osmline
+ SET indexed_status = 0, address = v.addr, token_info = v.ti
+ FROM (VALUES {}) as v(id, addr, ti)
+ WHERE place_id = v.id
+ """).format(_mk_valuelist("(%s, %s::hstore, %s::jsonb)", batch_size))
+
+
+ def index_places_params(self, place: DictRow) -> Sequence[Any]:
+ return (place['place_id'], place['address'],
+ _analyze_place(place, self.analyzer))
+
+
+
+class PostcodeRunner(Runner):
+ """ Provides the SQL commands for indexing the location_postcode table.
+ """
+
+ def name(self) -> str:
+ return "postcodes (location_postcode)"
+
+
+ def sql_count_objects(self) -> Query:
+ return 'SELECT count(*) FROM location_postcode WHERE indexed_status > 0'
+
+
+ def sql_get_objects(self) -> Query:
+ return """SELECT place_id FROM location_postcode
+ WHERE indexed_status > 0
+ ORDER BY country_code, postcode"""
+
+
+ def index_places_query(self, batch_size: int) -> Query:
+ return pysql.SQL("""UPDATE location_postcode SET indexed_status = 0
+ WHERE place_id IN ({})""")\
+ .format(pysql.SQL(',').join((pysql.Placeholder() for _ in range(batch_size))))
+
+
+ def index_places_params(self, place: DictRow) -> Sequence[Any]:
+ return (place['place_id'], )
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Path settings for extra data used by Nominatim.
+"""
+from pathlib import Path
+
+PHPLIB_DIR = (Path(__file__) / '..' / '..' / '..' / 'lib-php').resolve()
+SQLLIB_DIR = (Path(__file__) / '..' / '..' / '..' / 'lib-sql').resolve()
+DATA_DIR = (Path(__file__) / '..' / '..' / '..' / 'data').resolve()
+CONFIG_DIR = (Path(__file__) / '..' / '..' / '..' / 'settings').resolve()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Abstract class definitions for tokenizers. These base classes are here
from typing import List, Tuple, Dict, Any, Optional, Iterable
from pathlib import Path
-from nominatim.config import Configuration
-from nominatim.db.connection import Connection
-from nominatim.data.place_info import PlaceInfo
-from nominatim.typing import Protocol
+from ..typing import Protocol
+from ..config import Configuration
+from ..db.connection import Connection
+from ..data.place_info import PlaceInfo
class AbstractAnalyzer(ABC):
""" The analyzer provides the functions for analysing names and building
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for creating a tokenizer or initialising the right one for an
import importlib
from pathlib import Path
-from nominatim.errors import UsageError
-from nominatim.db import properties
-from nominatim.db.connection import connect
-from nominatim.config import Configuration
-from nominatim.tokenizer.base import AbstractTokenizer, TokenizerModule
+from ..errors import UsageError
+from ..db import properties
+from ..db.connection import connect
+from ..config import Configuration
+from ..tokenizer.base import AbstractTokenizer, TokenizerModule
LOG = logging.getLogger()
"Check the setting of NOMINATIM_TOKENIZER.", name)
raise UsageError('Tokenizer not found')
- return importlib.import_module('nominatim.tokenizer.' + name + '_tokenizer')
+ return importlib.import_module('nominatim_db.tokenizer.' + name + '_tokenizer')
def create_tokenizer(config: Configuration, init_db: bool = True,
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper class to create ICU rules from a configuration file.
from icu import Transliterator
-from nominatim.config import flatten_config_list, Configuration
-from nominatim.db.properties import set_property, get_property
-from nominatim.db.connection import Connection
-from nominatim.errors import UsageError
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.tokenizer.icu_token_analysis import ICUTokenAnalysis
-from nominatim.tokenizer.token_analysis.base import AnalysisModule, Analyzer
-import nominatim.data.country_info
+from ..config import flatten_config_list, Configuration
+from ..db.properties import set_property, get_property
+from ..db.connection import Connection
+from ..errors import UsageError
+from .place_sanitizer import PlaceSanitizer
+from .icu_token_analysis import ICUTokenAnalysis
+from .token_analysis.base import AnalysisModule, Analyzer
+from ..data import country_info
LOG = logging.getLogger()
config='TOKENIZER_CONFIG')
# Make sure country information is available to analyzers and sanitizers.
- nominatim.data.country_info.setup_country_config(config)
+ country_info.setup_country_config(config)
self.normalization_rules = self._cfg_to_icu_rules(rules, 'normalization')
self.transliteration_rules = self._cfg_to_icu_rules(rules, 'transliteration')
raise UsageError("'analyzer' parameter needs to be simple string")
self._analysis_mod: AnalysisModule = \
- config.load_plugin_module(analyzer_name, 'nominatim.tokenizer.token_analysis')
+ config.load_plugin_module(analyzer_name, 'nominatim_db.tokenizer.token_analysis')
self.config = self._analysis_mod.configure(rules, normalizer,
transliterator)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Container class collecting all components required to transform an OSM name
from typing import Mapping, Optional, TYPE_CHECKING
from icu import Transliterator
-from nominatim.tokenizer.token_analysis.base import Analyzer
+from .token_analysis.base import Analyzer
if TYPE_CHECKING:
from typing import Any
- from nominatim.tokenizer.icu_rule_loader import TokenAnalyzerRule # pylint: disable=cyclic-import
+ from .icu_rule_loader import TokenAnalyzerRule # pylint: disable=cyclic-import
class ICUTokenAnalysis:
""" Container class collecting the transliterators and token analysis
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tokenizer implementing normalisation as used before Nominatim 4 but using
from typing import Optional, Sequence, List, Tuple, Mapping, Any, cast, \
Dict, Set, Iterable
import itertools
-import json
import logging
from pathlib import Path
from textwrap import dedent
-from nominatim.db.connection import connect, Connection, Cursor
-from nominatim.config import Configuration
-from nominatim.db.utils import CopyBuffer
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.data.place_info import PlaceInfo
-from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.place_name import PlaceName
-from nominatim.tokenizer.icu_token_analysis import ICUTokenAnalysis
-from nominatim.tokenizer.base import AbstractAnalyzer, AbstractTokenizer
+from psycopg.types.json import Jsonb
+from psycopg import sql as pysql
+
+from ..db.connection import connect, Connection, Cursor, server_version_tuple,\
+ drop_tables, table_exists, execute_scalar
+from ..config import Configuration
+from ..db.sql_preprocessor import SQLPreprocessor
+from ..data.place_info import PlaceInfo
+from ..data.place_name import PlaceName
+from .icu_rule_loader import ICURuleLoader
+from .place_sanitizer import PlaceSanitizer
+from .icu_token_analysis import ICUTokenAnalysis
+from .base import AbstractAnalyzer, AbstractTokenizer
DBCFG_TERM_NORMALIZATION = "tokenizer_term_normalization"
""" Recompute frequencies for all name words.
"""
with connect(self.dsn) as conn:
- if not conn.table_exists('search_name'):
+ if not table_exists(conn, 'search_name'):
return
with conn.cursor() as cur:
cur.execute('ANALYSE search_name')
if threads > 1:
- cur.execute('SET max_parallel_workers_per_gather TO %s',
- (min(threads, 6),))
+ cur.execute(pysql.SQL('SET max_parallel_workers_per_gather TO {}')
+ .format(pysql.Literal(min(threads, 6),)))
- if conn.server_version_tuple() < (12, 0):
+ if server_version_tuple(conn) < (12, 0):
LOG.info('Computing word frequencies')
- cur.drop_table('word_frequencies')
- cur.drop_table('addressword_frequencies')
+ drop_tables(conn, 'word_frequencies', 'addressword_frequencies')
cur.execute("""CREATE TEMP TABLE word_frequencies AS
SELECT unnest(name_vector) as id, count(*)
FROM search_name GROUP BY id""")
$$ LANGUAGE plpgsql IMMUTABLE;
""")
LOG.info('Update word table with recomputed frequencies')
- cur.drop_table('tmp_word')
+ drop_tables(conn, 'tmp_word')
cur.execute("""CREATE TABLE tmp_word AS
SELECT word_id, word_token, type, word,
word_freq_update(word_id, info) as info
FROM word
""")
- cur.drop_table('word_frequencies')
- cur.drop_table('addressword_frequencies')
+ drop_tables(conn, 'word_frequencies', 'addressword_frequencies')
else:
LOG.info('Computing word frequencies')
- cur.drop_table('word_frequencies')
- cur.execute('ANALYSE search_name')
- cur.execute('ANALYSE word')
+ drop_tables(conn, 'word_frequencies')
cur.execute("""
CREATE TEMP TABLE word_frequencies AS
WITH word_freq AS MATERIALIZED (
cur.execute('CREATE UNIQUE INDEX ON word_frequencies(id) INCLUDE(info)')
cur.execute('ANALYSE word_frequencies')
LOG.info('Update word table with recomputed frequencies')
- cur.drop_table('tmp_word')
+ drop_tables(conn, 'tmp_word')
cur.execute("""CREATE TABLE tmp_word AS
SELECT word_id, word_token, type, word,
(CASE WHEN wf.info is null THEN word.info
ON word.word_id = wf.id
ORDER BY word_id
""")
- cur.drop_table('word_frequencies')
+ drop_tables(conn, 'word_frequencies')
with conn.cursor() as cur:
cur.execute('SET max_parallel_workers_per_gather TO 0')
""" Remove unused house numbers.
"""
with connect(self.dsn) as conn:
- if not conn.table_exists('search_name'):
+ if not table_exists(conn, 'search_name'):
return
with conn.cursor(name="hnr_counter") as cur:
cur.execute("""SELECT DISTINCT word_id, coalesce(info->>'lookup', word_token)
frequencies.
"""
with connect(self.dsn) as conn:
- with conn.cursor() as cur:
- cur.drop_table('word')
+ drop_tables(conn, 'word')
sqlp = SQLPreprocessor(conn, config)
sqlp.run_string(conn, """
CREATE TABLE word (
""" Rename all tables and indexes used by the tokenizer.
"""
with connect(self.dsn) as conn:
+ drop_tables(conn, 'word')
with conn.cursor() as cur:
- cur.drop_table('word')
cur.execute(f"ALTER TABLE {old} RENAME TO word")
for idx in ('word_token', 'word_id'):
cur.execute(f"""ALTER INDEX idx_{old}_{idx}
def __init__(self, dsn: str, sanitizer: PlaceSanitizer,
token_analysis: ICUTokenAnalysis) -> None:
- self.conn: Optional[Connection] = connect(dsn).connection
+ self.conn: Optional[Connection] = connect(dsn)
self.conn.autocommit = True
self.sanitizer = sanitizer
self.token_analysis = token_analysis
if terms:
with self.conn.cursor() as cur:
- cur.execute_values("""SELECT create_postcode_word(pc, var)
- FROM (VALUES %s) AS v(pc, var)""",
- terms)
+ cur.executemany("""SELECT create_postcode_word(%s, %s)""", terms)
to_add = new_phrases - existing_phrases
added = 0
- with CopyBuffer() as copystr:
+ with cursor.copy('COPY word(word_token, type, word, info) FROM STDIN') as copy:
for word, cls, typ, oper in to_add:
term = self._search_normalized(word)
if term:
- copystr.add(term, 'S', word,
- json.dumps({'class': cls, 'type': typ,
- 'op': oper if oper in ('in', 'near') else None}))
+ copy.write_row((term, 'S', word,
+ Jsonb({'class': cls, 'type': typ,
+ 'op': oper if oper in ('in', 'near') else None})))
added += 1
- copystr.copy_out(cursor, 'word',
- columns=['word_token', 'type', 'word', 'info'])
-
return added
to_delete = existing_phrases - new_phrases
if to_delete:
- cursor.execute_values(
- """ DELETE FROM word USING (VALUES %s) as v(name, in_class, in_type, op)
- WHERE type = 'S' and word = name
- and info->>'class' = in_class and info->>'type' = in_type
- and ((op = '-' and info->>'op' is null) or op = info->>'op')
+ cursor.executemany(
+ """ DELETE FROM word
+ WHERE type = 'S' and word = %s
+ and info->>'class' = %s and info->>'type' = %s
+ and %s = coalesce(info->>'op', '-')
""", to_delete)
return len(to_delete)
gone_tokens.update(existing_tokens[False] & word_tokens)
if gone_tokens:
cur.execute("""DELETE FROM word
- USING unnest(%s) as token
+ USING unnest(%s::text[]) as token
WHERE type = 'C' and word = %s
and word_token = token""",
(list(gone_tokens), country_code))
if internal:
sql = """INSERT INTO word (word_token, type, word, info)
(SELECT token, 'C', %s, '{"internal": "yes"}'
- FROM unnest(%s) as token)
+ FROM unnest(%s::text[]) as token)
"""
else:
sql = """INSERT INTO word (word_token, type, word)
(SELECT token, 'C', %s
- FROM unnest(%s) as token)
+ FROM unnest(%s::text[]) as token)
"""
cur.execute(sql, (country_code, list(new_tokens)))
if norm_name:
result = self._cache.housenumbers.get(norm_name, result)
if result[0] is None:
- with self.conn.cursor() as cur:
- hid = cur.scalar("SELECT getorcreate_hnr_id(%s)", (norm_name, ))
+ hid = execute_scalar(self.conn, "SELECT getorcreate_hnr_id(%s)", (norm_name, ))
- result = hid, norm_name
- self._cache.housenumbers[norm_name] = result
+ result = hid, norm_name
+ self._cache.housenumbers[norm_name] = result
else:
# Otherwise use the analyzer to determine the canonical name.
# Per convention we use the first variant as the 'lookup name', the
if result[0] is None:
variants = analyzer.compute_variants(word_id)
if variants:
- with self.conn.cursor() as cur:
- hid = cur.scalar("SELECT create_analyzed_hnr_id(%s, %s)",
+ hid = execute_scalar(self.conn, "SELECT create_analyzed_hnr_id(%s, %s)",
(word_id, list(variants)))
- result = hid, variants[0]
- self._cache.housenumbers[word_id] = result
+ result = hid, variants[0]
+ self._cache.housenumbers[word_id] = result
return result
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tokenizer implementing normalisation as used before Nominatim 4.
from textwrap import dedent
from icu import Transliterator
-import psycopg2
-import psycopg2.extras
-
-from nominatim.db.connection import connect, Connection
-from nominatim.config import Configuration
-from nominatim.db import properties
-from nominatim.db import utils as db_utils
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.data.place_info import PlaceInfo
-from nominatim.errors import UsageError
-from nominatim.tokenizer.base import AbstractAnalyzer, AbstractTokenizer
+import psycopg
+from psycopg import sql as pysql
+
+from ..errors import UsageError
+from ..db.connection import connect, Connection, drop_tables, table_exists,\
+ execute_scalar, register_hstore
+from ..config import Configuration
+from ..db import properties
+from ..db import utils as db_utils
+from ..db.sql_preprocessor import SQLPreprocessor
+from ..data.place_info import PlaceInfo
+from .base import AbstractAnalyzer, AbstractTokenizer
DBCFG_NORMALIZATION = "tokenizer_normalization"
DBCFG_MAXWORDFREQ = "tokenizer_maxwordfreq"
"""
with conn.cursor() as cur:
try:
- cur.execute("""CREATE FUNCTION nominatim_test_import_func(text)
- RETURNS text AS %s, 'transliteration'
- LANGUAGE c IMMUTABLE STRICT;
- DROP FUNCTION nominatim_test_import_func(text)
- """, (f'{module_dir}/nominatim.so', ))
- except psycopg2.DatabaseError as err:
+ cur.execute(pysql.SQL("""CREATE FUNCTION nominatim_test_import_func(text)
+ RETURNS text AS {}, 'transliteration'
+ LANGUAGE c IMMUTABLE STRICT;
+ DROP FUNCTION nominatim_test_import_func(text)
+ """).format(pysql.Literal(f'{module_dir}/nominatim.so')))
+ except psycopg.DatabaseError as err:
LOG.fatal("Error accessing database module: %s", err)
raise UsageError("Database module cannot be accessed.") from err
* Can nominatim.so be accessed by the database user?
"""
with connect(self.dsn) as conn:
- with conn.cursor() as cur:
- try:
- out = cur.scalar("SELECT make_standard_name('a')")
- except psycopg2.Error as err:
- return hint.format(error=str(err))
+ try:
+ out = execute_scalar(conn, "SELECT make_standard_name('a')")
+ except psycopg.Error as err:
+ return hint.format(error=str(err))
if out != 'a':
return hint.format(error='Unexpected result for make_standard_name()')
""" Recompute the frequency of full words.
"""
with connect(self.dsn) as conn:
- if conn.table_exists('search_name'):
+ if table_exists(conn, 'search_name'):
+ drop_tables(conn, "word_frequencies")
with conn.cursor() as cur:
- cur.drop_table("word_frequencies")
LOG.info("Computing word frequencies")
cur.execute("""CREATE TEMP TABLE word_frequencies AS
SELECT unnest(name_vector) as id, count(*)
cur.execute("""UPDATE word SET search_name_count = count
FROM word_frequencies
WHERE word_token like ' %' and word_id = id""")
- cur.drop_table("word_frequencies")
+ drop_tables(conn, "word_frequencies")
conn.commit()
"""
def __init__(self, dsn: str, normalizer: Any):
- self.conn: Optional[Connection] = connect(dsn).connection
+ self.conn: Optional[Connection] = connect(dsn)
self.conn.autocommit = True
self.normalizer = normalizer
- psycopg2.extras.register_hstore(self.conn)
+ register_hstore(self.conn)
self._cache = _TokenCache(self.conn)
""", (to_delete, ))
if to_add:
cur.execute("""SELECT count(create_postcode_id(pc))
- FROM unnest(%s) as pc
+ FROM unnest(%s::text[]) as pc
""", (to_add, ))
with self.conn.cursor() as cur:
# Get the old phrases.
existing_phrases = set()
- cur.execute("""SELECT word, class, type, operator FROM word
+ cur.execute("""SELECT word, class as cls, type, operator FROM word
WHERE class != 'place'
OR (type != 'house' AND type != 'postcode')""")
for label, cls, typ, oper in cur:
to_delete = existing_phrases - norm_phrases
if to_add:
- cur.execute_values(
+ cur.executemany(
""" INSERT INTO word (word_id, word_token, word, class, type,
search_name_count, operator)
(SELECT nextval('seq_word'), ' ' || make_standard_name(name), name,
class, type, 0,
CASE WHEN op in ('in', 'near') THEN op ELSE null END
- FROM (VALUES %s) as v(name, class, type, op))""",
+ FROM (VALUES (%s, %s, %s, %s)) as v(name, class, type, op))""",
to_add)
if to_delete and should_replace:
- cur.execute_values(
- """ DELETE FROM word USING (VALUES %s) as v(name, in_class, in_type, op)
+ cur.executemany(
+ """ DELETE FROM word
+ USING (VALUES (%s, %s, %s, %s)) as v(name, in_class, in_type, op)
WHERE word = name and class = in_class and type = in_type
and ((op = '-' and operator is null) or op = operator)""",
to_delete)
"""INSERT INTO word (word_id, word_token, country_code)
(SELECT nextval('seq_word'), lookup_token, %s
FROM (SELECT DISTINCT ' ' || make_standard_name(n) as lookup_token
- FROM unnest(%s)n) y
+ FROM unnest(%s::TEXT[])n) y
WHERE NOT EXISTS(SELECT * FROM word
WHERE word_token = lookup_token and country_code = %s))
""", (country_code, list(names.values()), country_code))
def add_names(self, conn: Connection, names: Mapping[str, str]) -> None:
""" Add token information for the names of the place.
"""
- with conn.cursor() as cur:
- # Create the token IDs for all names.
- self.data['names'] = cur.scalar("SELECT make_keywords(%s)::text",
+ # Create the token IDs for all names.
+ self.data['names'] = execute_scalar(conn, "SELECT make_keywords(%s)::text",
(names, ))
""" Add addr:street match terms.
"""
def _get_street(name: str) -> Optional[str]:
- with conn.cursor() as cur:
- return cast(Optional[str],
- cur.scalar("SELECT word_ids_from_name(%s)::text", (name, )))
+ return cast(Optional[str],
+ execute_scalar(conn, "SELECT word_ids_from_name(%s)::text", (name, )))
tokens = self.cache.streets.get(street, _get_street)
self.data['street'] = tokens or '{}'
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Handler for cleaning name and address tags in place information before it
"""
from typing import Optional, List, Mapping, Sequence, Callable, Any, Tuple
-from nominatim.errors import UsageError
-from nominatim.config import Configuration
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
-from nominatim.tokenizer.sanitizers.base import SanitizerHandler, ProcessInfo
-from nominatim.data.place_name import PlaceName
-from nominatim.data.place_info import PlaceInfo
+from ..errors import UsageError
+from ..config import Configuration
+from .sanitizers.config import SanitizerConfig
+from .sanitizers.base import SanitizerHandler, ProcessInfo
+from ..data.place_name import PlaceName
+from ..data.place_info import PlaceInfo
class PlaceSanitizer:
raise UsageError("'step' attribute must be a simple string.")
module: SanitizerHandler = \
- config.load_plugin_module(func['step'], 'nominatim.tokenizer.sanitizers')
+ config.load_plugin_module(func['step'], 'nominatim_db.tokenizer.sanitizers')
self.handlers.append(module.create(SanitizerConfig(func)))
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Common data types and protocols for sanitizers.
"""
from typing import Optional, List, Mapping, Callable
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
-from nominatim.data.place_info import PlaceInfo
-from nominatim.data.place_name import PlaceName
-from nominatim.typing import Protocol, Final
+from ...typing import Protocol, Final
+from ...data.place_info import PlaceInfo
+from ...data.place_name import PlaceName
+from .config import SanitizerConfig
class ProcessInfo:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Sanitizer that preprocesses address tags for house numbers. The sanitizer
"""
from typing import Callable, Iterator, List
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.data.place_name import PlaceName
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from ...data.place_name import PlaceName
+from .base import ProcessInfo
+from .config import SanitizerConfig
class _HousenumberSanitizer:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Sanitizer that filters postcodes by their officially allowed pattern.
"""
from typing import Callable, Optional, Tuple
-from nominatim.data.postcode_format import PostcodeFormatter
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from ...data.postcode_format import PostcodeFormatter
+from .base import ProcessInfo
+from .config import SanitizerConfig
class _PostcodeSanitizer:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Sanitizer that preprocesses tags from the TIGER import.
from typing import Callable
import re
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from .base import ProcessInfo
+from .config import SanitizerConfig
COUNTY_MATCH = re.compile('(.*), [A-Z][A-Z]')
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Configuration for Sanitizers.
from collections import UserDict
import re
-from nominatim.errors import UsageError
+from ...errors import UsageError
# working around missing generics in Python < 3.8
# See https://github.com/python/typing/issues/60#issuecomment-869757075
-# SPDX-License-Identifier: GPL-2.0-only\r
+# SPDX-License-Identifier: GPL-3.0-or-later\r
#\r
# This file is part of Nominatim. (https://nominatim.org)\r
#\r
-# Copyright (C) 2023 by the Nominatim developer community.\r
+# Copyright (C) 2024 by the Nominatim developer community.\r
# For a full list of authors see the git log.\r
"""\r
Sanitizer which prevents certain tags from getting into the search index.\r
"""\r
from typing import Callable, List, Tuple, Sequence\r
\r
-from nominatim.tokenizer.sanitizers.base import ProcessInfo\r
-from nominatim.data.place_name import PlaceName\r
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig\r
+from ...data.place_name import PlaceName\r
+from .base import ProcessInfo\r
+from .config import SanitizerConfig\r
\r
class _TagSanitizer:\r
\r
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Sanitizer that splits lists of names into their components.
"""
from typing import Callable
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from .base import ProcessInfo
+from .config import SanitizerConfig
def create(config: SanitizerConfig) -> Callable[[ProcessInfo], None]:
""" Create a name processing function that splits name values with
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
This sanitizer creates additional name variants for names that have
"""
from typing import Callable
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from .base import ProcessInfo
+from .config import SanitizerConfig
def create(_: SanitizerConfig) -> Callable[[ProcessInfo], None]:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
This sanitizer sets the `analyzer` property depending on the
"""
from typing import Callable, Dict, Optional, List
-from nominatim.data import country_info
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from ...data import country_info
+from .base import ProcessInfo
+from .config import SanitizerConfig
class _AnalyzerByLanguage:
""" Processor for tagging the language of names in a place.
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
This sanitizer maps OSM data to Japanese block addresses.
from typing import Callable
from typing import List, Optional
-from nominatim.tokenizer.sanitizers.base import ProcessInfo
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
-from nominatim.data.place_name import PlaceName
+from .base import ProcessInfo
+from .config import SanitizerConfig
+from ...data.place_name import PlaceName
def create(_: SanitizerConfig) -> Callable[[ProcessInfo], None]:
"""Set up the sanitizer
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Common data types and protocols for analysers.
"""
from typing import Mapping, List, Any
-from nominatim.typing import Protocol
-from nominatim.data.place_name import PlaceName
+from ...typing import Protocol
+from ...data.place_name import PlaceName
class Analyzer(Protocol):
""" The `create()` function of an analysis module needs to return an
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Parser for configuration for variants.
import itertools
import re
-from nominatim.config import flatten_config_list
-from nominatim.errors import UsageError
+from ...config import flatten_config_list
+from ...errors import UsageError
class ICUVariant(NamedTuple):
""" A single replacement rule for variant creation.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Generic processor for names that creates abbreviation variants.
import datrie
-from nominatim.errors import UsageError
-from nominatim.data.place_name import PlaceName
-from nominatim.tokenizer.token_analysis.config_variants import get_variant_config
-from nominatim.tokenizer.token_analysis.generic_mutation import MutationVariantGenerator
+from ...errors import UsageError
+from ...data.place_name import PlaceName
+from .config_variants import get_variant_config
+from .generic_mutation import MutationVariantGenerator
### Configuration section
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Creator for mutation variants for the generic token analysis.
import logging
import re
-from nominatim.errors import UsageError
+from ...errors import UsageError
LOG = logging.getLogger()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Specialized processor for housenumbers. Analyses common housenumber patterns
from typing import Any, List, cast
import re
-from nominatim.data.place_name import PlaceName
-from nominatim.tokenizer.token_analysis.generic_mutation import MutationVariantGenerator
+from ...data.place_name import PlaceName
+from .generic_mutation import MutationVariantGenerator
RE_NON_DIGIT = re.compile('[^0-9]')
RE_DIGIT_ALPHA = re.compile(r'(\d)\s*([^\d\s␣])')
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
"""
from typing import Any, List
-from nominatim.tokenizer.token_analysis.generic_mutation import MutationVariantGenerator
-from nominatim.data.place_name import PlaceName
+from ...data.place_name import PlaceName
+from .generic_mutation import MutationVariantGenerator
### Configuration section
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module with functions for importing, updating Nominatim databases
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Function to add additional OSM data from a file or the API into the database.
import logging
import urllib
-from nominatim.db.connection import connect
-from nominatim.tools.exec_utils import run_osm2pgsql, get_url
+from ..db.connection import connect
+from ..utils.url_utils import get_url
+from .exec_utils import run_osm2pgsql
LOG = logging.getLogger()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for database analysis and maintenance.
from typing import Optional, Tuple, Any, cast
import logging
-from psycopg2.extras import Json, register_hstore
-from psycopg2 import DataError
+import psycopg
+from psycopg.types.json import Json
-from nominatim.config import Configuration
-from nominatim.db.connection import connect, Cursor
-from nominatim.tokenizer import factory as tokenizer_factory
-from nominatim.errors import UsageError
-from nominatim.data.place_info import PlaceInfo
-from nominatim.typing import DictCursorResult
+from ..typing import DictCursorResult
+from ..config import Configuration
+from ..db.connection import connect, Cursor, register_hstore
+from ..errors import UsageError
+from ..tokenizer import factory as tokenizer_factory
+from ..data.place_info import PlaceInfo
LOG = logging.getLogger()
"""
with connect(config.get_libpq_dsn()) as conn:
register_hstore(conn)
- with conn.cursor() as cur:
+ with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
place = _get_place_info(cur, osm_id, place_id)
cur.execute("update placex set indexed_status = 2 where place_id = %s",
tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
+ # Enable printing of messages.
+ conn.add_notice_handler(lambda diag: print(diag.message_primary))
+
with tokenizer.name_analyzer() as analyzer:
cur.execute("""UPDATE placex
SET indexed_status = 0, address = %s, token_info = %s,
# we do not want to keep the results
conn.rollback()
- for msg in conn.notices:
- print(msg)
-
def clean_deleted_relations(config: Configuration, age: str) -> None:
""" Clean deleted relations older than a given age
WHERE p.osm_type = d.osm_type AND p.osm_id = d.osm_id
AND age(p.indexed_date) > %s::interval""",
(age, ))
- except DataError as exc:
+ except psycopg.DataError as exc:
raise UsageError('Invalid PostgreSQL time interval format') from exc
conn.commit()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Collection of functions that check if the database is complete and functional.
from enum import Enum
from textwrap import dedent
-from nominatim.config import Configuration
-from nominatim.db.connection import connect, Connection
-from nominatim.db import properties
-from nominatim.errors import UsageError
-from nominatim.tokenizer import factory as tokenizer_factory
-from nominatim.tools import freeze
-from nominatim.version import NOMINATIM_VERSION, parse_version
+from ..config import Configuration
+from ..db.connection import connect, Connection, server_version_tuple,\
+ index_exists, table_exists, execute_scalar
+from ..db import properties
+from ..errors import UsageError
+from ..tokenizer import factory as tokenizer_factory
+from . import freeze
+from ..version import NOMINATIM_VERSION, parse_version
CHECKLIST = []
""" Run a number of checks on the database and return the status.
"""
try:
- conn = connect(config.get_libpq_dsn()).connection
+ conn = connect(config.get_libpq_dsn())
except UsageError as err:
conn = _BadConnection(str(err)) # type: ignore[assignment]
'idx_postcode_id',
'idx_postcode_postcode'
]
- if conn.table_exists('search_name'):
+ if table_exists(conn, 'search_name'):
indexes.extend(('idx_search_name_nameaddress_vector',
'idx_search_name_name_vector',
'idx_search_name_centroid'))
- if conn.server_version_tuple() >= (11, 0, 0):
+ if server_version_tuple(conn) >= (11, 0, 0):
indexes.extend(('idx_placex_housenumber',
'idx_osmline_parent_osm_id_with_hnr'))
- if conn.table_exists('place'):
+ if table_exists(conn, 'place'):
indexes.extend(('idx_location_area_country_place_id',
'idx_place_osm_unique',
'idx_placex_rank_address_sector',
Hints:
* Are you connecting to the correct database?
-
+
{instruction}
Check the Migration chapter of the Administration Guide.
""" Checking database_version matches Nominatim software version
"""
- if conn.table_exists('nominatim_properties'):
+ if table_exists(conn, 'nominatim_properties'):
db_version_str = properties.get_property(conn, 'database_version')
else:
db_version_str = None
def check_placex_table(conn: Connection, config: Configuration) -> CheckResult:
""" Checking for placex table
"""
- if conn.table_exists('placex'):
+ if table_exists(conn, 'placex'):
return CheckState.OK
return CheckState.FATAL, dict(config=config)
def check_placex_size(conn: Connection, _: Configuration) -> CheckResult:
""" Checking for placex content
"""
- with conn.cursor() as cur:
- cnt = cur.scalar('SELECT count(*) FROM (SELECT * FROM placex LIMIT 100) x')
+ cnt = execute_scalar(conn, 'SELECT count(*) FROM (SELECT * FROM placex LIMIT 100) x')
return CheckState.OK if cnt > 0 else CheckState.FATAL
def check_existance_wikipedia(conn: Connection, _: Configuration) -> CheckResult:
""" Checking for wikipedia/wikidata data
"""
- if not conn.table_exists('search_name') or not conn.table_exists('place'):
+ if not table_exists(conn, 'search_name') or not table_exists(conn, 'place'):
return CheckState.NOT_APPLICABLE
- with conn.cursor() as cur:
- if conn.table_exists('wikimedia_importance'):
- cnt = cur.scalar('SELECT count(*) FROM wikimedia_importance')
- else:
- cnt = cur.scalar('SELECT count(*) FROM wikipedia_article')
+ if table_exists(conn, 'wikimedia_importance'):
+ cnt = execute_scalar(conn, 'SELECT count(*) FROM wikimedia_importance')
+ else:
+ cnt = execute_scalar(conn, 'SELECT count(*) FROM wikipedia_article')
- return CheckState.WARN if cnt == 0 else CheckState.OK
+ return CheckState.WARN if cnt == 0 else CheckState.OK
@_check(hint="""\
def check_indexing(conn: Connection, _: Configuration) -> CheckResult:
""" Checking indexing status
"""
- with conn.cursor() as cur:
- cnt = cur.scalar('SELECT count(*) FROM placex WHERE indexed_status > 0')
+ cnt = execute_scalar(conn, 'SELECT count(*) FROM placex WHERE indexed_status > 0')
if cnt == 0:
return CheckState.OK
Low counts of unindexed places are fine."""
return CheckState.WARN, dict(count=cnt, index_cmd=index_cmd)
- if conn.index_exists('idx_placex_rank_search'):
+ if index_exists(conn, 'idx_placex_rank_search'):
# Likely just an interrupted update.
index_cmd = 'nominatim index'
else:
"""
missing = []
for index in _get_indexes(conn):
- if not conn.index_exists(index):
+ if not index_exists(conn, index):
missing.append(index)
if missing:
if not config.get_bool('USE_US_TIGER_DATA'):
return CheckState.NOT_APPLICABLE
- if not conn.table_exists('location_property_tiger'):
+ if not table_exists(conn, 'location_property_tiger'):
return CheckState.FAIL, dict(error='TIGER data table not found.')
- with conn.cursor() as cur:
- if cur.scalar('SELECT count(*) FROM location_property_tiger') == 0:
- return CheckState.FAIL, dict(error='TIGER data table is empty.')
+ if execute_scalar(conn, 'SELECT count(*) FROM location_property_tiger') == 0:
+ return CheckState.FAIL, dict(error='TIGER data table is empty.')
return CheckState.OK
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Collection of host system information including software versions, memory,
import subprocess
import sys
from pathlib import Path
-from typing import List, Optional, Tuple, Union
+from typing import List, Optional, Union
import psutil
-from psycopg2.extensions import make_dsn, parse_dsn
-from nominatim.config import Configuration
-from nominatim.db.connection import connect
-from nominatim.version import NOMINATIM_VERSION
-
-
-def convert_version(ver_tup: Tuple[int, int]) -> str:
- """converts tuple version (ver_tup) to a string representation"""
- return ".".join(map(str, ver_tup))
+from ..config import Configuration
+from ..db.connection import connect, server_version_tuple, execute_scalar
+from ..version import NOMINATIM_VERSION
def friendly_memory_string(mem: float) -> str:
"""Generate a report about the host system including software versions, memory,
storage, and database configuration."""
- with connect(make_dsn(config.get_libpq_dsn(), dbname='postgres')) as conn:
- postgresql_ver: str = convert_version(conn.server_version_tuple())
+ with connect(config.get_libpq_dsn(), dbname='postgres') as conn:
+ postgresql_ver: str = '.'.join(map(str, server_version_tuple(conn)))
with conn.cursor() as cur:
- num = cur.scalar("SELECT count(*) FROM pg_catalog.pg_database WHERE datname=%s",
- (parse_dsn(config.get_libpq_dsn())['dbname'], ))
- nominatim_db_exists = num == 1 if isinstance(num, int) else False
+ cur.execute("SELECT datname FROM pg_catalog.pg_database WHERE datname=%s",
+ (config.get_database_params()['dbname'], ))
+ nominatim_db_exists = cur.rowcount > 0
if nominatim_db_exists:
with connect(config.get_libpq_dsn()) as conn:
- postgis_ver: str = convert_version(conn.postgis_version_tuple())
+ postgis_ver: str = execute_scalar(conn, 'SELECT postgis_lib_version()')
else:
postgis_ver = "Unable to connect to database"
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Exporting a Nominatim database to SQlite.
import sqlalchemy as sa
-from nominatim.typing import SaSelect, SaRow
-from nominatim.db.sqlalchemy_types import Geometry, IntArray
-from nominatim.api.search.query_analyzer_factory import make_query_analyzer
-import nominatim.api as napi
+import nominatim_api as napi
+from nominatim_api.search.query_analyzer_factory import make_query_analyzer
+from nominatim_api.typing import SaSelect, SaRow
+from nominatim_api.sql.sqlalchemy_types import Geometry, IntArray
LOG = logging.getLogger()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for setting up and importing a new Nominatim database.
from typing import Tuple, Optional, Union, Sequence, MutableMapping, Any
import logging
import os
-import selectors
import subprocess
+import asyncio
from pathlib import Path
import psutil
-from psycopg2 import sql as pysql
-
-from nominatim.config import Configuration
-from nominatim.db.connection import connect, get_pg_env, Connection
-from nominatim.db.async_connection import DBConnection
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.tools.exec_utils import run_osm2pgsql
-from nominatim.errors import UsageError
-from nominatim.version import POSTGRESQL_REQUIRED_VERSION, \
- POSTGIS_REQUIRED_VERSION
+import psycopg
+from psycopg import sql as pysql
+
+from ..errors import UsageError
+from ..config import Configuration
+from ..db.connection import connect, get_pg_env, Connection, server_version_tuple,\
+ postgis_version_tuple, drop_tables, table_exists, execute_scalar
+from ..db.sql_preprocessor import SQLPreprocessor
+from ..db.query_pool import QueryPool
+from .exec_utils import run_osm2pgsql
+from ..version import POSTGRESQL_REQUIRED_VERSION, POSTGIS_REQUIRED_VERSION
LOG = logging.getLogger()
def _require_loaded(extension_name: str, conn: Connection) -> None:
""" Check that the given extension is loaded. """
- if not conn.extension_loaded(extension_name):
- LOG.fatal('Required module %s is not loaded.', extension_name)
- raise UsageError(f'{extension_name} is not loaded.')
+ with conn.cursor() as cur:
+ cur.execute('SELECT * FROM pg_extension WHERE extname = %s', (extension_name, ))
+ if cur.rowcount <= 0:
+ LOG.fatal('Required module %s is not loaded.', extension_name)
+ raise UsageError(f'{extension_name} is not loaded.')
def check_existing_database_plugins(dsn: str) -> None:
""" Check that the database has the required plugins installed."""
with connect(dsn) as conn:
_require_version('PostgreSQL server',
- conn.server_version_tuple(),
+ server_version_tuple(conn),
POSTGRESQL_REQUIRED_VERSION)
_require_version('PostGIS',
- conn.postgis_version_tuple(),
+ postgis_version_tuple(conn),
POSTGIS_REQUIRED_VERSION)
_require_loaded('hstore', conn)
with connect(dsn) as conn:
_require_version('PostgreSQL server',
- conn.server_version_tuple(),
+ server_version_tuple(conn),
POSTGRESQL_REQUIRED_VERSION)
if rouser is not None:
- with conn.cursor() as cur:
- cnt = cur.scalar('SELECT count(*) FROM pg_user where usename = %s',
+ cnt = execute_scalar(conn, 'SELECT count(*) FROM pg_user where usename = %s',
(rouser, ))
- if cnt == 0:
- LOG.fatal("Web user '%s' does not exist. Create it with:\n"
- "\n createuser %s", rouser, rouser)
- raise UsageError('Missing read-only user.')
+ if cnt == 0:
+ LOG.fatal("Web user '%s' does not exist. Create it with:\n"
+ "\n createuser %s", rouser, rouser)
+ raise UsageError('Missing read-only user.')
# Create extensions.
with conn.cursor() as cur:
cur.execute('CREATE EXTENSION IF NOT EXISTS hstore')
cur.execute('CREATE EXTENSION IF NOT EXISTS postgis')
- postgis_version = conn.postgis_version_tuple()
+ postgis_version = postgis_version_tuple(conn)
if postgis_version[0] >= 3:
cur.execute('CREATE EXTENSION IF NOT EXISTS postgis_raster')
conn.commit()
_require_version('PostGIS',
- conn.postgis_version_tuple(),
+ postgis_version_tuple(conn),
POSTGIS_REQUIRED_VERSION)
with connect(options['dsn']) as conn:
if not ignore_errors:
with conn.cursor() as cur:
- cur.execute('SELECT * FROM place LIMIT 1')
+ cur.execute('SELECT true FROM place LIMIT 1')
if cur.rowcount == 0:
raise UsageError('No data imported by osm2pgsql.')
if drop:
- conn.drop_table('planet_osm_nodes')
+ drop_tables(conn, 'planet_osm_nodes')
+ conn.commit()
if drop and options['flatnode_file']:
Path(options['flatnode_file']).unlink()
cur.execute('TRUNCATE location_property_tiger')
cur.execute('TRUNCATE location_property_osmline')
cur.execute('TRUNCATE location_postcode')
- if conn.table_exists('search_name'):
+ if table_exists(conn, 'search_name'):
cur.execute('TRUNCATE search_name')
cur.execute('DROP SEQUENCE IF EXISTS seq_place')
cur.execute('CREATE SEQUENCE seq_place start 100000')
'extratags', 'geometry')))
-def load_data(dsn: str, threads: int) -> None:
+async def load_data(dsn: str, threads: int) -> None:
""" Copy data into the word and placex table.
"""
- sel = selectors.DefaultSelector()
- # Then copy data from place to placex in <threads - 1> chunks.
- place_threads = max(1, threads - 1)
- for imod in range(place_threads):
- conn = DBConnection(dsn)
- conn.connect()
- conn.perform(
- pysql.SQL("""INSERT INTO placex ({columns})
- SELECT {columns} FROM place
- WHERE osm_id % {total} = {mod}
- AND NOT (class='place' and (type='houses' or type='postcode'))
- AND ST_IsValid(geometry)
- """).format(columns=_COPY_COLUMNS,
- total=pysql.Literal(place_threads),
- mod=pysql.Literal(imod)))
- sel.register(conn, selectors.EVENT_READ, conn)
-
- # Address interpolations go into another table.
- conn = DBConnection(dsn)
- conn.connect()
- conn.perform("""INSERT INTO location_property_osmline (osm_id, address, linegeo)
- SELECT osm_id, address, geometry FROM place
- WHERE class='place' and type='houses' and osm_type='W'
- and ST_GeometryType(geometry) = 'ST_LineString'
- """)
- sel.register(conn, selectors.EVENT_READ, conn)
-
- # Now wait for all of them to finish.
- todo = place_threads + 1
- while todo > 0:
- for key, _ in sel.select(1):
- conn = key.data
- sel.unregister(conn)
- conn.wait()
- conn.close()
- todo -= 1
+ placex_threads = max(1, threads - 1)
+
+ progress = asyncio.create_task(_progress_print())
+
+ async with QueryPool(dsn, placex_threads + 1) as pool:
+ # Copy data from place to placex in <threads - 1> chunks.
+ for imod in range(placex_threads):
+ await pool.put_query(
+ pysql.SQL("""INSERT INTO placex ({columns})
+ SELECT {columns} FROM place
+ WHERE osm_id % {total} = {mod}
+ AND NOT (class='place'
+ and (type='houses' or type='postcode'))
+ AND ST_IsValid(geometry)
+ """).format(columns=_COPY_COLUMNS,
+ total=pysql.Literal(placex_threads),
+ mod=pysql.Literal(imod)), None)
+
+ # Interpolations need to be copied seperately
+ await pool.put_query("""
+ INSERT INTO location_property_osmline (osm_id, address, linegeo)
+ SELECT osm_id, address, geometry FROM place
+ WHERE class='place' and type='houses' and osm_type='W'
+ and ST_GeometryType(geometry) = 'ST_LineString' """, None)
+
+ progress.cancel()
+
+ async with await psycopg.AsyncConnection.connect(dsn) as aconn:
+ await aconn.execute('ANALYSE')
+
+
+async def _progress_print() -> None:
+ while True:
+ try:
+ await asyncio.sleep(1)
+ except asyncio.CancelledError:
+ print('', flush=True)
+ break
print('.', end='', flush=True)
- print('\n')
-
- with connect(dsn) as syn_conn:
- with syn_conn.cursor() as cur:
- cur.execute('ANALYSE')
-def create_search_indices(conn: Connection, config: Configuration,
+async def create_search_indices(conn: Connection, config: Configuration,
drop: bool = False, threads: int = 1) -> None:
""" Create tables that have explicit partitioning.
"""
sql = SQLPreprocessor(conn, config)
- sql.run_parallel_sql_file(config.get_libpq_dsn(),
- 'indices.sql', min(8, threads), drop=drop)
+ await sql.run_parallel_sql_file(config.get_libpq_dsn(),
+ 'indices.sql', min(8, threads), drop=drop)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper functions for executing external programs.
"""
-from typing import Any, Mapping, IO
+from typing import Any, Mapping
import logging
import os
import subprocess
-import urllib.request as urlrequest
+import shutil
-from nominatim.typing import StrPath
-from nominatim.version import NOMINATIM_VERSION
-from nominatim.db.connection import get_pg_env
+from ..typing import StrPath
+from ..db.connection import get_pg_env
LOG = logging.getLogger()
""" Run osm2pgsql with the given options.
"""
env = get_pg_env(options['dsn'])
- cmd = [str(options['osm2pgsql']),
+
+ cmd = [_find_osm2pgsql_cmd(options['osm2pgsql']),
'--slim',
'--log-progress', 'true',
'--number-processes', '1' if options['append'] else str(options['threads']),
env=env, check=True)
-def get_url(url: str) -> str:
- """ Get the contents from the given URL and return it as a UTF-8 string.
- """
- headers = {"User-Agent": f"Nominatim/{NOMINATIM_VERSION!s}"}
-
- try:
- request = urlrequest.Request(url, headers=headers)
- with urlrequest.urlopen(request) as response: # type: IO[bytes]
- return response.read().decode('utf-8')
- except Exception:
- LOG.fatal('Failed to load URL: %s', url)
- raise
+def _find_osm2pgsql_cmd(cmdline: str) -> str:
+ if cmdline is not None:
+ return cmdline
+
+ in_path = shutil.which('osm2pgsql')
+ if in_path is None:
+ raise RuntimeError('osm2pgsql executable not found. Please install osm2pgsql first.')
+
+ return str(in_path)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for removing unnecessary data from the database.
from typing import Optional
from pathlib import Path
-from psycopg2 import sql as pysql
+from psycopg import sql as pysql
-from nominatim.db.connection import Connection
+from ..db.connection import Connection, drop_tables, table_exists
UPDATE_TABLES = [
'address_levels',
+ pysql.SQL(' or ').join(parts))
tables = [r[0] for r in cur]
- for table in tables:
- cur.drop_table(table, cascade=True)
-
+ drop_tables(conn, *tables, cascade=True)
conn.commit()
""" Returns true if database is in a frozen state
"""
- return conn.table_exists('place') is False
+ return table_exists(conn, 'place') is False
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for database migration to newer software versions.
from typing import List, Tuple, Callable, Any
import logging
-from psycopg2 import sql as pysql
+from psycopg import sql as pysql
-from nominatim.config import Configuration
-from nominatim.db import properties
-from nominatim.db.connection import connect, Connection
-from nominatim.version import NominatimVersion, NOMINATIM_VERSION, parse_version
-from nominatim.tools import refresh
-from nominatim.tokenizer import factory as tokenizer_factory
-from nominatim.errors import UsageError
+from ..errors import UsageError
+from ..config import Configuration
+from ..db import properties
+from ..db.connection import connect, Connection, server_version_tuple,\
+ table_has_column, table_exists, execute_scalar, register_hstore
+from ..version import NominatimVersion, NOMINATIM_VERSION, parse_version
+from ..tokenizer import factory as tokenizer_factory
+from . import refresh
LOG = logging.getLogger()
if necesssary.
"""
with connect(config.get_libpq_dsn()) as conn:
- if conn.table_exists('nominatim_properties'):
+ register_hstore(conn)
+ if table_exists(conn, 'nominatim_properties'):
db_version_str = properties.get_property(conn, 'database_version')
else:
db_version_str = None
Only migrations for 3.6 and later are supported, so bail out
when the version seems older.
"""
- with conn.cursor() as cur:
- # In version 3.6, the country_name table was updated. Check for that.
- cnt = cur.scalar("""SELECT count(*) FROM
- (SELECT svals(name) FROM country_name
- WHERE country_code = 'gb')x;
- """)
- if cnt < 100:
- LOG.fatal('It looks like your database was imported with a version '
- 'prior to 3.6.0. Automatic migration not possible.')
- raise UsageError('Migration not possible.')
+ # In version 3.6, the country_name table was updated. Check for that.
+ cnt = execute_scalar(conn, """SELECT count(*) FROM
+ (SELECT svals(name) FROM country_name
+ WHERE country_code = 'gb')x;
+ """)
+ if cnt < 100:
+ LOG.fatal('It looks like your database was imported with a version '
+ 'prior to 3.6.0. Automatic migration not possible.')
+ raise UsageError('Migration not possible.')
return NominatimVersion(3, 5, 0, 99)
def add_nominatim_property_table(conn: Connection, config: Configuration, **_: Any) -> None:
""" Add nominatim_property table.
"""
- if not conn.table_exists('nominatim_properties'):
+ if not table_exists(conn, 'nominatim_properties'):
with conn.cursor() as cur:
cur.execute(pysql.SQL("""CREATE TABLE nominatim_properties (
property TEXT,
configuration for the backwards-compatible legacy tokenizer
"""
if properties.get_property(conn, 'tokenizer') is None:
- with conn.cursor() as cur:
- for table in ('placex', 'location_property_osmline'):
- has_column = cur.scalar("""SELECT count(*) FROM information_schema.columns
- WHERE table_name = %s
- and column_name = 'token_info'""",
- (table, ))
- if has_column == 0:
+ for table in ('placex', 'location_property_osmline'):
+ if not table_has_column(conn, table, 'token_info'):
+ with conn.cursor() as cur:
cur.execute(pysql.SQL('ALTER TABLE {} ADD COLUMN token_info JSONB')
.format(pysql.Identifier(table)))
tokenizer = tokenizer_factory.create_tokenizer(config, init_db=False,
The inclusion is needed for efficient lookup of housenumbers in
full address searches.
"""
- if conn.server_version_tuple() >= (11, 0, 0):
+ if server_version_tuple(conn) >= (11, 0, 0):
with conn.cursor() as cur:
cur.execute(""" CREATE INDEX IF NOT EXISTS
idx_location_property_tiger_housenumber_migrated
Also converts the data into the stricter format which requires that
startnumbers comply with the odd/even requirements.
"""
- if conn.table_has_column('location_property_osmline', 'step'):
+ if table_has_column(conn, 'location_property_osmline', 'step'):
return
with conn.cursor() as cur:
def add_step_column_for_tiger(conn: Connection, **_: Any) -> None:
""" Add a new column 'step' to the tiger data table.
"""
- if conn.table_has_column('location_property_tiger', 'step'):
+ if table_has_column(conn, 'location_property_tiger', 'step'):
return
with conn.cursor() as cur:
""" Add a new column 'derived_name' which in the future takes the
country names as imported from OSM data.
"""
- if not conn.table_has_column('country_name', 'derived_name'):
+ if not table_has_column(conn, 'country_name', 'derived_name'):
with conn.cursor() as cur:
cur.execute("ALTER TABLE country_name ADD COLUMN derived_name public.HSTORE")
""" Names from the country table should be marked as internal to prevent
them from being deleted. Only necessary for ICU tokenizer.
"""
- import psycopg2.extras # pylint: disable=import-outside-toplevel
-
tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
with tokenizer.name_analyzer() as analyzer:
with conn.cursor() as cur:
- psycopg2.extras.register_hstore(cur)
cur.execute("SELECT country_code, name FROM country_name")
for country_code, names in cur:
The table is only necessary when updates are possible, i.e.
the database is not in freeze mode.
"""
- if conn.table_exists('place'):
+ if table_exists(conn, 'place'):
with conn.cursor() as cur:
cur.execute("""CREATE TABLE IF NOT EXISTS place_to_be_deleted (
osm_type CHAR(1),
def split_pending_index(conn: Connection, **_: Any) -> None:
""" Reorganise indexes for pending updates.
"""
- if conn.table_exists('place'):
+ if table_exists(conn, 'place'):
with conn.cursor() as cur:
cur.execute("""CREATE INDEX IF NOT EXISTS idx_placex_rank_address_sector
ON placex USING BTREE (rank_address, geometry_sector)
def enable_forward_dependencies(conn: Connection, **_: Any) -> None:
""" Create indexes for updates with forward dependency tracking (long-running).
"""
- if conn.table_exists('planet_osm_ways'):
+ if table_exists(conn, 'planet_osm_ways'):
with conn.cursor() as cur:
cur.execute("""SELECT * FROM pg_indexes
WHERE tablename = 'planet_osm_ways'
def create_postcode_parent_index(conn: Connection, **_: Any) -> None:
""" Create index needed for updating postcodes when a parent changes.
"""
- if conn.table_exists('planet_osm_ways'):
+ if table_exists(conn, 'planet_osm_ways'):
with conn.cursor() as cur:
cur.execute("""CREATE INDEX IF NOT EXISTS
idx_location_postcode_parent_place_id
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for importing, updating and otherwise maintaining the table
import logging
from math import isfinite
-from psycopg2 import sql as pysql
+from psycopg import sql as pysql
-from nominatim.db.connection import connect, Connection
-from nominatim.utils.centroid import PointsCentroid
-from nominatim.data.postcode_format import PostcodeFormatter, CountryPostcodeMatcher
-from nominatim.tokenizer.base import AbstractAnalyzer, AbstractTokenizer
+from ..db.connection import connect, Connection, table_exists
+from ..utils.centroid import PointsCentroid
+from ..data.postcode_format import PostcodeFormatter, CountryPostcodeMatcher
+from ..tokenizer.base import AbstractAnalyzer, AbstractTokenizer
LOG = logging.getLogger()
with conn.cursor() as cur:
if to_add:
- cur.execute_values(
+ cur.executemany(pysql.SQL(
"""INSERT INTO location_postcode
(place_id, indexed_status, country_code,
- postcode, geometry) VALUES %s""",
- to_add,
- template=pysql.SQL("""(nextval('seq_place'), 1, {},
- %s, 'SRID=4326;POINT(%s %s)')
- """).format(pysql.Literal(self.country)))
+ postcode, geometry)
+ VALUES (nextval('seq_place'), 1, {}, %s,
+ ST_SetSRID(ST_MakePoint(%s, %s), 4326))
+ """).format(pysql.Literal(self.country)),
+ to_add)
if to_delete:
cur.execute("""DELETE FROM location_postcode
WHERE country_code = %s and postcode = any(%s)
""", (self.country, to_delete))
if to_update:
- cur.execute_values(
+ cur.executemany(
pysql.SQL("""UPDATE location_postcode
SET indexed_status = 2,
- geometry = ST_SetSRID(ST_Point(v.x, v.y), 4326)
- FROM (VALUES %s) AS v (pc, x, y)
- WHERE country_code = {} and postcode = pc
- """).format(pysql.Literal(self.country)), to_update)
+ geometry = ST_SetSRID(ST_Point(%s, %s), 4326)
+ WHERE country_code = {} and postcode = %s
+ """).format(pysql.Literal(self.country)),
+ to_update)
def _compute_changes(self, conn: Connection) \
- -> Tuple[List[Tuple[str, float, float]], List[str], List[Tuple[str, float, float]]]:
+ -> Tuple[List[Tuple[str, float, float]], List[str], List[Tuple[float, float, str]]]:
""" Compute which postcodes from the collected postcodes have to be
added or modified and which from the location_postcode table
have to be deleted.
if pcobj:
newx, newy = pcobj.centroid()
if (x - newx) > 0.0000001 or (y - newy) > 0.0000001:
- to_update.append((postcode, newx, newy))
+ to_update.append((newx, newy, postcode))
else:
to_delete.append(postcode)
postcodes can be computed.
"""
with connect(dsn) as conn:
- return conn.table_exists('place')
+ return table_exists(conn, 'place')
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for bringing auxiliary data in the database up-to-date.
from textwrap import dedent
from pathlib import Path
-from psycopg2 import sql as pysql
+from psycopg import sql as pysql
-from nominatim.config import Configuration
-from nominatim.db.connection import Connection, connect
-from nominatim.db.utils import execute_file, CopyBuffer
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.version import NOMINATIM_VERSION
+from ..config import Configuration
+from ..db.connection import Connection, connect, postgis_version_tuple,\
+ drop_tables, table_exists
+from ..db.utils import execute_file
+from ..db.sql_preprocessor import SQLPreprocessor
+from ..version import NOMINATIM_VERSION
LOG = logging.getLogger()
for entry in levels:
_add_address_level_rows_from_entry(rows, entry)
- with conn.cursor() as cur:
- cur.drop_table(table)
+ drop_tables(conn, table)
+ with conn.cursor() as cur:
cur.execute(pysql.SQL("""CREATE TABLE {} (
country_code varchar(2),
class TEXT,
rank_address SMALLINT)
""").format(pysql.Identifier(table)))
- cur.execute_values(pysql.SQL("INSERT INTO {} VALUES %s")
- .format(pysql.Identifier(table)), rows)
+ cur.executemany(pysql.SQL("INSERT INTO {} VALUES (%s, %s, %s, %s, %s)")
+ .format(pysql.Identifier(table)), rows)
cur.execute(pysql.SQL('CREATE UNIQUE INDEX ON {} (country_code, class, type)')
.format(pysql.Identifier(table)))
if not data_file.exists():
return 1
- # Only import the first occurance of a wikidata ID.
+ # Only import the first occurrence of a wikidata ID.
# This keeps indexes and table small.
wd_done = set()
with connect(dsn) as conn:
+ drop_tables(conn, 'wikipedia_article', 'wikipedia_redirect', 'wikimedia_importance')
with conn.cursor() as cur:
- cur.drop_table('wikipedia_article')
- cur.drop_table('wikipedia_redirect')
- cur.drop_table('wikimedia_importance')
cur.execute("""CREATE TABLE wikimedia_importance (
language TEXT NOT NULL,
title TEXT NOT NULL,
wikidata TEXT
) """)
- with gzip.open(str(data_file), 'rt') as fd, CopyBuffer() as buf:
- for row in csv.DictReader(fd, delimiter='\t', quotechar='|'):
- wd_id = int(row['wikidata_id'][1:])
- buf.add(row['language'], row['title'], row['importance'],
- None if wd_id in wd_done else row['wikidata_id'])
- wd_done.add(wd_id)
-
- if buf.size() > 10000000:
- with conn.cursor() as cur:
- buf.copy_out(cur, 'wikimedia_importance',
- columns=['language', 'title', 'importance',
- 'wikidata'])
+ copy_cmd = """COPY wikimedia_importance(language, title, importance, wikidata)
+ FROM STDIN"""
+ with gzip.open(str(data_file), 'rt') as fd, cur.copy(copy_cmd) as copy:
+ for row in csv.DictReader(fd, delimiter='\t', quotechar='|'):
+ wd_id = int(row['wikidata_id'][1:])
+ copy.write_row((row['language'],
+ row['title'],
+ row['importance'],
+ None if wd_id in wd_done else row['wikidata_id']))
+ wd_done.add(wd_id)
- with conn.cursor() as cur:
- buf.copy_out(cur, 'wikimedia_importance',
- columns=['language', 'title', 'importance', 'wikidata'])
-
- with conn.cursor() as cur:
cur.execute("""CREATE INDEX IF NOT EXISTS idx_wikimedia_importance_title
ON wikimedia_importance (title)""")
cur.execute("""CREATE INDEX IF NOT EXISTS idx_wikimedia_importance_wikidata
return 1
with connect(dsn) as conn:
- postgis_version = conn.postgis_version_tuple()
+ postgis_version = postgis_version_tuple(conn)
if postgis_version[0] < 3:
LOG.error('PostGIS version is too old for using OSM raster data.')
return 2
template = "\nrequire_once(CONST_LibDir.'/website/{}');\n"
- search_name_table_exists = bool(conn and conn.table_exists('search_name'))
+ search_name_table_exists = bool(conn and table_exists(conn, 'search_name'))
for script in WEBSITE_SCRIPTS:
if not search_name_table_exists and script == 'search.php':
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for updating a database from a replication source.
import urllib.request as urlrequest
import requests
-from nominatim.db import status
-from nominatim.db.connection import Connection, connect
-from nominatim.tools.exec_utils import run_osm2pgsql
-from nominatim.errors import UsageError
+
+from ..errors import UsageError
+from ..db import status
+from ..db.connection import Connection, connect, server_version_tuple
+from .exec_utils import run_osm2pgsql
try:
from osmium.replication.server import ReplicationServer
# Consume updates with osm2pgsql.
options['append'] = True
- options['disable_jit'] = conn.server_version_tuple() >= (11, 0)
+ options['disable_jit'] = server_version_tuple(conn) >= (11, 0)
run_osm2pgsql(options)
# Handle deletions
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Contains the class which handles statistics for the
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module containing the SPCsvLoader class.
from typing import Iterable
import csv
import os
-from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
-from nominatim.errors import UsageError
+
+from ...errors import UsageError
+from .special_phrase import SpecialPhrase
class SPCsvLoader:
"""
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module containing the class handling the import
import logging
import re
-from psycopg2.sql import Identifier, SQL
+from psycopg.sql import Identifier, SQL
-from nominatim.config import Configuration
-from nominatim.db.connection import Connection
-from nominatim.tools.special_phrases.importer_statistics import SpecialPhrasesImporterStatistics
-from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
-from nominatim.tokenizer.base import AbstractTokenizer
-from nominatim.typing import Protocol
+from ...typing import Protocol
+from ...config import Configuration
+from ...db.connection import Connection, drop_tables, index_exists
+from .importer_statistics import SpecialPhrasesImporterStatistics
+from .special_phrase import SpecialPhrase
+from ...tokenizer.base import AbstractTokenizer
LOG = logging.getLogger()
index_prefix = f'idx_place_classtype_{phrase_class}_{phrase_type}_'
base_table = _classtype_table(phrase_class, phrase_type)
# Index on centroid
- if not self.db_connection.index_exists(index_prefix + 'centroid'):
+ if not index_exists(self.db_connection, index_prefix + 'centroid'):
with self.db_connection.cursor() as db_cursor:
db_cursor.execute(SQL("CREATE INDEX {} ON {} USING GIST (centroid) {}")
.format(Identifier(index_prefix + 'centroid'),
SQL(sql_tablespace)))
# Index on place_id
- if not self.db_connection.index_exists(index_prefix + 'place_id'):
+ if not index_exists(self.db_connection, index_prefix + 'place_id'):
with self.db_connection.cursor() as db_cursor:
db_cursor.execute(SQL("CREATE INDEX {} ON {} USING btree(place_id) {}")
.format(Identifier(index_prefix + 'place_id'),
.format(Identifier(table_name),
Identifier(self.config.DATABASE_WEBUSER)))
+
def _remove_non_existent_tables_from_db(self) -> None:
"""
Remove special phrases which doesn't exist on the wiki anymore.
# Delete place_classtype tables corresponding to class/type which
# are not on the wiki anymore.
- with self.db_connection.cursor() as db_cursor:
- for table in self.table_phrases_to_delete:
- self.statistics_handler.notify_one_table_deleted()
- db_cursor.drop_table(table)
+ drop_tables(self.db_connection, *self.table_phrases_to_delete)
+ for _ in self.table_phrases_to_delete:
+ self.statistics_handler.notify_one_table_deleted()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module containing the SPWikiLoader class.
import re
import logging
-from nominatim.config import Configuration
-from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
-from nominatim.tools.exec_utils import get_url
+from ...config import Configuration
+from ...utils.url_utils import get_url
+from .special_phrase import SpecialPhrase
LOG = logging.getLogger()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Module containing the class SpecialPhrase.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for importing tiger data and handling tarbar and directory files
"""
-from typing import Any, TextIO, List, Union, cast
+from typing import Any, TextIO, List, Union, cast, Iterator, Dict
import csv
import io
import logging
import os
import tarfile
-from psycopg2.extras import Json
+from psycopg.types.json import Json
-from nominatim.config import Configuration
-from nominatim.db.connection import connect
-from nominatim.db.async_connection import WorkerPool
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.errors import UsageError
-from nominatim.data.place_info import PlaceInfo
-from nominatim.tokenizer.base import AbstractAnalyzer, AbstractTokenizer
-from nominatim.tools import freeze
+from ..config import Configuration
+from ..db.connection import connect
+from ..db.sql_preprocessor import SQLPreprocessor
+from ..errors import UsageError
+from ..db.query_pool import QueryPool
+from ..data.place_info import PlaceInfo
+from ..tokenizer.base import AbstractTokenizer
+from . import freeze
LOG = logging.getLogger()
self.tar_handle.close()
self.tar_handle = None
+ def __bool__(self) -> bool:
+ return bool(self.files)
- def next_file(self) -> TextIO:
+ def get_file(self, fname: Union[str, tarfile.TarInfo]) -> TextIO:
""" Return a file handle to the next file to be processed.
Raises an IndexError if there is no file left.
"""
- fname = self.files.pop(0)
-
if self.tar_handle is not None:
extracted = self.tar_handle.extractfile(fname)
assert extracted is not None
return open(cast(str, fname), encoding='utf-8')
- def __len__(self) -> int:
- return len(self.files)
-
-
-def handle_threaded_sql_statements(pool: WorkerPool, fd: TextIO,
- analyzer: AbstractAnalyzer) -> None:
- """ Handles sql statement with multiplexing
- """
- lines = 0
- # Using pool of database connections to execute sql statements
-
- sql = "SELECT tiger_line_import(%s, %s, %s, %s, %s, %s)"
-
- for row in csv.DictReader(fd, delimiter=';'):
- try:
- address = dict(street=row['street'], postcode=row['postcode'])
- args = ('SRID=4326;' + row['geometry'],
- int(row['from']), int(row['to']), row['interpolation'],
- Json(analyzer.process_place(PlaceInfo({'address': address}))),
- analyzer.normalize_postcode(row['postcode']))
- except ValueError:
- continue
- pool.next_free_worker().perform(sql, args=args)
-
- lines += 1
- if lines == 1000:
- print('.', end='', flush=True)
- lines = 0
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
+ """ Iterate over the lines in each file.
+ """
+ for fname in self.files:
+ fd = self.get_file(fname)
+ yield from csv.DictReader(fd, delimiter=';')
-def add_tiger_data(data_dir: str, config: Configuration, threads: int,
+async def add_tiger_data(data_dir: str, config: Configuration, threads: int,
tokenizer: AbstractTokenizer) -> int:
""" Import tiger data from directory or tar file `data dir`.
"""
dsn = config.get_libpq_dsn()
with connect(dsn) as conn:
- is_frozen = freeze.is_frozen(conn)
- conn.close()
-
- if is_frozen:
+ if freeze.is_frozen(conn):
raise UsageError("Tiger cannot be imported when database frozen (Github issue #3048)")
with TigerInput(data_dir) as tar:
# sql_query in <threads - 1> chunks.
place_threads = max(1, threads - 1)
- with WorkerPool(dsn, place_threads, ignore_sql_errors=True) as pool:
+ async with QueryPool(dsn, place_threads, autocommit=True) as pool:
with tokenizer.name_analyzer() as analyzer:
- while tar:
- with tar.next_file() as fd:
- handle_threaded_sql_statements(pool, fd, analyzer)
-
- print('\n')
+ lines = 0
+ for row in tar:
+ try:
+ address = dict(street=row['street'], postcode=row['postcode'])
+ args = ('SRID=4326;' + row['geometry'],
+ int(row['from']), int(row['to']), row['interpolation'],
+ Json(analyzer.process_place(PlaceInfo({'address': address}))),
+ analyzer.normalize_postcode(row['postcode']))
+ except ValueError:
+ continue
+
+ await pool.put_query(
+ """SELECT tiger_line_import(%s::GEOMETRY, %s::INT,
+ %s::INT, %s::TEXT, %s::JSONB, %s::TEXT)""",
+ args)
+
+ lines += 1
+ if lines == 1000:
+ print('.', end='', flush=True)
+ lines = 0
+
+ print('', flush=True)
LOG.warning("Creating indexes on Tiger data")
with connect(dsn) as conn:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Type definitions for typing annotations.
# pylint: disable=missing-class-docstring,useless-import-alias
if TYPE_CHECKING:
- import psycopg2.sql
- import psycopg2.extensions
- import psycopg2.extras
import os
StrPath = Union[str, 'os.PathLike[str]']
SysEnv = Mapping[str, str]
-# psycopg2-related types
-
-Query = Union[str, bytes, 'psycopg2.sql.Composable']
+# psycopg-related types
T_ResultKey = TypeVar('T_ResultKey', int, str)
DictCursorResults = Sequence[DictCursorResult]
-T_cursor = TypeVar('T_cursor', bound='psycopg2.extensions.cursor')
-
# The following typing features require typing_extensions to work
# on all supported Python versions.
# Only require this for type checking but not for normal operations.
Protocol = object
Final = 'Final'
TypedDict = dict
-
-
-# SQLAlchemy introduced generic types in version 2.0 making typing
-# incompatible with older versions. Add wrappers here so we don't have
-# to litter the code with bare-string types.
-
-if TYPE_CHECKING:
- import sqlalchemy as sa
- from typing_extensions import (TypeAlias as TypeAlias)
-else:
- TypeAlias = str
-
-SaLambdaSelect: TypeAlias = 'Union[sa.Select[Any], sa.StatementLambdaElement]'
-SaSelect: TypeAlias = 'sa.Select[Any]'
-SaScalarSelect: TypeAlias = 'sa.ScalarSelect[Any]'
-SaRow: TypeAlias = 'sa.Row[Any]'
-SaColumn: TypeAlias = 'sa.ColumnElement[Any]'
-SaExpression: TypeAlias = 'sa.ColumnElement[bool]'
-SaLabel: TypeAlias = 'sa.Label[Any]'
-SaFromClause: TypeAlias = 'sa.FromClause'
-SaSelectable: TypeAlias = 'sa.Selectable'
-SaBind: TypeAlias = 'sa.BindParameter[Any]'
-SaDialect: TypeAlias = 'sa.Dialect'
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Functions for computation of centroids.
--- /dev/null
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
+"""
+Helper functions for accessing URL.
+"""
+from typing import IO
+import logging
+import urllib.request as urlrequest
+
+from ..version import NOMINATIM_VERSION
+
+LOG = logging.getLogger()
+
+def get_url(url: str) -> str:
+ """ Get the contents from the given URL and return it as a UTF-8 string.
+
+ This version makes sure that an appropriate user agent is sent.
+ """
+ headers = {"User-Agent": f"Nominatim/{NOMINATIM_VERSION!s}"}
+
+ try:
+ request = urlrequest.Request(url, headers=headers)
+ with urlrequest.urlopen(request) as response: # type: IO[bytes]
+ return response.read().decode('utf-8')
+ except Exception:
+ LOG.fatal('Failed to load URL: %s', url)
+ raise
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Version information for Nominatim.
"""
-from typing import Optional, NamedTuple
+from typing import NamedTuple, Optional
+
+# See also https://github.com/PyCQA/pylint/issues/6006
+# pylint: disable=useless-import-alias,unused-import
class NominatimVersion(NamedTuple):
""" Version information for Nominatim. We follow semantic versioning.
db_patch_level: int
def __str__(self) -> str:
+ if self.db_patch_level is None:
+ return f"{self.major}.{self.minor}.{self.patch_level}"
+
return f"{self.major}.{self.minor}.{self.patch_level}-{self.db_patch_level}"
+ def release_version(self) -> str:
+ """ Return the release version in semantic versioning format.
-NOMINATIM_VERSION = NominatimVersion(4, 4, 99, 1)
+ The release version does not include the database patch version.
+ """
+ return f"{self.major}.{self.minor}.{self.patch_level}"
-POSTGRESQL_REQUIRED_VERSION = (9, 6)
-POSTGIS_REQUIRED_VERSION = (2, 2)
-
-# Cmake sets a variable @GIT_HASH@ by executing 'git --log'. It is not run
-# on every execution of 'make'.
-# cmake/tool-installed.tmpl is used to build the binary 'nominatim'. Inside
-# there is a call to set the variable value below.
-GIT_COMMIT_HASH : Optional[str] = None
def parse_version(version: str) -> NominatimVersion:
"""
parts = version.split('.')
return NominatimVersion(*[int(x) for x in parts[:2] + parts[2].split('-')])
+
+
+NOMINATIM_VERSION = parse_version('4.4.99-1')
+
+POSTGRESQL_REQUIRED_VERSION = (9, 6)
+POSTGIS_REQUIRED_VERSION = (2, 2)
+
+# Cmake sets a variable @GIT_HASH@ by executing 'git --log'. It is not run
+# on every execution of 'make'.
+# cmake/tool-installed.tmpl is used to build the binary 'nominatim'. Inside
+# there is a call to set the variable value below.
+GIT_COMMIT_HASH : Optional[str] = None
Feature: Searches with postcodes
Various searches involving postcodes
+ @v1-api-php-only
Scenario: US 5+4 ZIP codes are shortened to 5 ZIP codes if not found
When sending json search query "36067 1111, us" with address
Then result addresses contain
| postcode |
| 36067 |
+ And results contain
+ | type |
+ | postcode |
Scenario: Postcode search with address
When sending json search query "9486, mauren"
| AD675 |
+ @fail-legacy
Scenario: Different postcodes with the same normalization can both be found
Given the places
| osm | class | type | addr+postcode | addr+housenumber | geometry |
--- /dev/null
+@DB
+Feature: Reverse searches
+ Test results of reverse queries
+
+ @v1-api-python-only
+ Scenario: POI in POI area
+ Given the 0.0001 grid with origin 1,1
+ | 1 | | | | | | | | 2 |
+ | | 9 | | | | | | | |
+ | 4 | | | | | | | | 3 |
+ And the places
+ | osm | class | type | geometry |
+ | W1 | aeroway | terminal | (1,2,3,4,1) |
+ | N1 | amenity | restaurant | 9 |
+ When importing
+ And sending v1/reverse at 1.0001,1.0001
+ Then results contain
+ | osm |
+ | N1 |
+ When sending v1/reverse at 1.0003,1.0001
+ Then results contain
+ | osm |
+ | W1 |
| W1 |
+ @fail-legacy
Scenario Outline: Special cased american states will be found
Given the grid
| 1 | | 2 |
| R1 | boundary | administrative | rel | 8 | (10,11,12,13,10) |
And the places
| osm | class | type | name+name:de |
- | N3 | place | city | pnt |
+ | N3 | place | city | greeny |
And the relations
| id | members |
| 1 | N3:label |
When importing
Then placex contains
| object | linked_place_id | name+_place_name:de |
- | R1 | - | pnt |
+ | R1 | - | greeny |
And placex contains
| object | linked_place_id | name+name:de |
- | N3 | R1 | pnt |
+ | N3 | R1 | greeny |
When updating places
| osm | class | type | name+name:de |
| N3 | place | city | newname |
| R1 | boundary | administrative | rel | 8 | (10,11,12,13,10) |
And the places
| osm | class | type | name |
- | N3 | place | city | pnt |
+ | N3 | place | city | greeny |
And the relations
| id | members |
| 1 | N3:label |
When importing
Then placex contains
| object | linked_place_id | name+_place_name | name+name |
- | R1 | - | pnt | rel |
+ | R1 | - | greeny | rel |
And placex contains
| object | linked_place_id | name+name |
- | N3 | R1 | pnt |
- When sending search query "pnt"
+ | N3 | R1 | greeny |
+ When sending search query "greeny"
Then results contain
| osm |
| R1 |
And placex contains
| object | linked_place_id | name+_place_name:de | name+name |
| R1 | - | depnt | rel |
- When sending search query "pnt"
+ When sending search query "greeny"
Then exactly 0 results are returned
Scenario: Updating linkee extratags keeps linker's extratags
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
from pathlib import Path
+import sys
from behave import *
+sys.path.insert(1, str(Path(__file__, '..', '..', '..', 'src').resolve()))
+
from steps.geometry_factory import GeometryFactory
from steps.nominatim_environment import NominatimEnvironment
-TEST_BASE_DIR = Path(__file__) / '..' / '..'
+TEST_BASE_DIR = Path(__file__, '..', '..').resolve()
userconfig = {
- 'BUILDDIR' : (TEST_BASE_DIR / '..' / 'build').resolve(),
'REMOVE_TEMPLATE' : False,
'KEEP_TEST_DB' : False,
'DB_HOST' : None,
'TEMPLATE_DB' : 'test_template_nominatim',
'TEST_DB' : 'test_nominatim',
'API_TEST_DB' : 'test_api_nominatim',
- 'API_TEST_FILE' : (TEST_BASE_DIR / 'testdb' / 'apidb-test-data.pbf').resolve(),
+ 'API_TEST_FILE' : TEST_BASE_DIR / 'testdb' / 'apidb-test-data.pbf',
'SERVER_MODULE_PATH' : None,
'TOKENIZER' : None, # Test with a custom tokenizer
'STYLE' : 'extratags',
- 'API_ENGINE': 'falcon',
- 'PHPCOV' : False, # set to output directory to enable code coverage
+ 'API_ENGINE': 'falcon'
}
use_step_matcher("re")
+++ /dev/null
-<?php
-/**
- * SPDX-License-Identifier: GPL-2.0-only
- *
- * This file is part of Nominatim. (https://nominatim.org)
- *
- * Copyright (C) 2022 by the Nominatim developer community.
- * For a full list of authors see the git log.
- */
-require_once 'SebastianBergmann/CodeCoverage/autoload.php';
-
-
-function coverage_shutdown($oCoverage)
-{
- $oCoverage->stop();
- $writer = new \SebastianBergmann\CodeCoverage\Report\PHP;
- $writer->process($oCoverage, $_SERVER['PHP_CODE_COVERAGE_FILE']);
-}
-
-$covfilter = new SebastianBergmann\CodeCoverage\Filter();
-if (method_exists($covfilter, 'addDirectoryToWhitelist')) {
- // pre PHPUnit 9
- $covfilter->addDirectoryToWhitelist($_SERVER['COV_PHP_DIR'].'/lib-php');
- $covfilter->addDirectoryToWhitelist($_SERVER['COV_PHP_DIR'].'/website');
- $coverage = new SebastianBergmann\CodeCoverage\CodeCoverage(null, $covfilter);
-} else {
- // since PHP Uit 9
- $covfilter->includeDirectory($_SERVER['COV_PHP_DIR'].'/lib-php');
- $covfilter->includeDirectory($_SERVER['COV_PHP_DIR'].'/website');
- $coverage = new SebastianBergmann\CodeCoverage\CodeCoverage(
- (new SebastianBergmann\CodeCoverage\Driver\Selector)->forLineCoverage($covfilter),
- $covfilter
- );
-}
-
-$coverage->start($_SERVER['COV_TEST_NAME']);
-
-register_shutdown_function('coverage_shutdown', $coverage);
-
-include $_SERVER['COV_SCRIPT_FILENAME'];
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
from pathlib import Path
import importlib
-import sys
import tempfile
-import psycopg2
-import psycopg2.extras
+import psycopg
+from psycopg import sql as pysql
-sys.path.insert(1, str((Path(__file__) / '..' / '..' / '..' / '..').resolve()))
-
-from nominatim import cli
-from nominatim.config import Configuration
-from nominatim.db.connection import Connection
-from nominatim.tools import refresh
-from nominatim.tokenizer import factory as tokenizer_factory
+from nominatim_db import cli
+from nominatim_db.config import Configuration
+from nominatim_db.db.connection import Connection, register_hstore, execute_scalar
+from nominatim_db.tools import refresh
+from nominatim_db.tokenizer import factory as tokenizer_factory
from steps.utils import run_script
class NominatimEnvironment:
"""
def __init__(self, config):
- self.build_dir = Path(config['BUILDDIR']).resolve()
self.src_dir = (Path(__file__) / '..' / '..' / '..' / '..').resolve()
self.db_host = config['DB_HOST']
self.db_port = config['DB_PORT']
self.server_module_path = config['SERVER_MODULE_PATH']
self.reuse_template = not config['REMOVE_TEMPLATE']
self.keep_scenario_db = config['KEEP_TEST_DB']
- self.code_coverage_path = config['PHPCOV']
- self.code_coverage_id = 1
self.default_config = Configuration(None).get_os_env()
self.test_env = None
raise RuntimeError(f"Unknown API engine '{config['API_ENGINE']}'")
self.api_engine = getattr(self, f"create_api_request_func_{config['API_ENGINE']}")()
+ if self.tokenizer == 'legacy' and self.server_module_path is None:
+ raise RuntimeError("You must set -DSERVER_MODULE_PATH when testing the legacy tokenizer.")
+
def connect_database(self, dbname):
""" Return a connection to the database with the given name.
Uses configured host, user and port.
"""
- dbargs = {'database': dbname}
+ dbargs = {'dbname': dbname, 'row_factory': psycopg.rows.dict_row}
if self.db_host:
dbargs['host'] = self.db_host
if self.db_port:
dbargs['user'] = self.db_user
if self.db_pass:
dbargs['password'] = self.db_pass
- conn = psycopg2.connect(connection_factory=Connection, **dbargs)
- return conn
+ return psycopg.connect(**dbargs)
- def next_code_coverage_file(self):
- """ Generate the next name for a coverage file.
- """
- fn = Path(self.code_coverage_path) / "{:06d}.cov".format(self.code_coverage_id)
- self.code_coverage_id += 1
-
- return fn.resolve()
def write_nominatim_config(self, dbname):
""" Set up a custom test configuration that connects to the given
self.test_env['NOMINATIM_DATADIR'] = str((self.src_dir / 'data').resolve())
self.test_env['NOMINATIM_SQLDIR'] = str((self.src_dir / 'lib-sql').resolve())
self.test_env['NOMINATIM_CONFIGDIR'] = str((self.src_dir / 'settings').resolve())
- self.test_env['NOMINATIM_DATABASE_MODULE_SRC_PATH'] = str((self.build_dir / 'module').resolve())
- self.test_env['NOMINATIM_OSM2PGSQL_BINARY'] = str((self.build_dir / 'osm2pgsql' / 'osm2pgsql').resolve())
if self.tokenizer is not None:
self.test_env['NOMINATIM_TOKENIZER'] = self.tokenizer
if self.import_style is not None:
if self.server_module_path:
self.test_env['NOMINATIM_DATABASE_MODULE_PATH'] = self.server_module_path
- else:
- # avoid module being copied into the temporary environment
- self.test_env['NOMINATIM_DATABASE_MODULE_PATH'] = str((self.build_dir / 'module').resolve())
if self.website_dir is not None:
self.website_dir.cleanup()
conn = False
refresh.setup_website(Path(self.website_dir.name) / 'website',
self.get_test_config(), conn)
+ if conn:
+ conn.close()
def get_test_config(self):
cfg = Configuration(Path(self.website_dir.name), environ=self.test_env)
- cfg.set_libdirs(module=self.build_dir / 'module',
- osm2pgsql=self.build_dir / 'osm2pgsql' / 'osm2pgsql')
+ cfg.set_libdirs(module=self.server_module_path)
return cfg
def get_libpq_dsn(self):
def db_drop_database(self, name):
""" Drop the database with the given name.
"""
- conn = self.connect_database('postgres')
- conn.set_isolation_level(0)
- cur = conn.cursor()
- cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
- conn.close()
+ with self.connect_database('postgres') as conn:
+ conn.autocommit = True
+ conn.execute(pysql.SQL('DROP DATABASE IF EXISTS')
+ + pysql.Identifier(name))
def setup_template_db(self):
""" Setup a template database that already contains common test data.
""" Setup a test against a fresh, empty test database.
"""
self.setup_template_db()
- conn = self.connect_database(self.template_db)
- conn.set_isolation_level(0)
- cur = conn.cursor()
- cur.execute('DROP DATABASE IF EXISTS {}'.format(self.test_db))
- cur.execute('CREATE DATABASE {} TEMPLATE = {}'.format(self.test_db, self.template_db))
- conn.close()
+ with self.connect_database(self.template_db) as conn:
+ conn.autocommit = True
+ conn.execute(pysql.SQL('DROP DATABASE IF EXISTS')
+ + pysql.Identifier(self.test_db))
+ conn.execute(pysql.SQL('CREATE DATABASE {} TEMPLATE = {}').format(
+ pysql.Identifier(self.test_db),
+ pysql.Identifier(self.template_db)))
+
self.write_nominatim_config(self.test_db)
context.db = self.connect_database(self.test_db)
context.db.autocommit = True
- psycopg2.extras.register_hstore(context.db, globally=False)
+ register_hstore(context.db)
def teardown_db(self, context, force_drop=False):
""" Remove the test database, if it exists.
dropped and always false returned.
"""
if self.reuse_template:
- conn = self.connect_database('postgres')
- with conn.cursor() as cur:
- cur.execute('select count(*) from pg_database where datname = %s',
- (name,))
- if cur.fetchone()[0] == 1:
+ with self.connect_database('postgres') as conn:
+ num = execute_scalar(conn,
+ 'select count(*) from pg_database where datname = %s',
+ (name,))
+ if num == 1:
return True
- conn.close()
else:
self.db_drop_database(name)
return False
+
def reindex_placex(self, db):
""" Run the indexing step until all data in the placex has
been processed. Indexing during updates can produce more data
to index under some circumstances. That is why indexing may have
to be run multiple times.
"""
- with db.cursor() as cur:
- while True:
- self.run_nominatim('index')
+ self.run_nominatim('index')
- cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
- if cur.rowcount == 0:
- return
def run_nominatim(self, *cmdline):
""" Run the nominatim command-line tool via the library.
if self.website_dir is not None:
cmdline = list(cmdline) + ['--project-dir', self.website_dir.name]
- cli.nominatim(module_dir='',
- osm2pgsql_path=str(self.build_dir / 'osm2pgsql' / 'osm2pgsql'),
+ cli.nominatim(module_dir=self.server_module_path,
+ osm2pgsql_path=None,
cli_args=cmdline,
environ=self.test_env)
def create_api_request_func_starlette(self):
- import nominatim.server.starlette.server
+ import nominatim_api.server.starlette.server
from asgi_lifespan import LifespanManager
import httpx
async def _request(endpoint, params, project_dir, environ, http_headers):
- app = nominatim.server.starlette.server.get_application(project_dir, environ)
+ app = nominatim_api.server.starlette.server.get_application(project_dir, environ)
async with LifespanManager(app):
async with httpx.AsyncClient(app=app, base_url="http://nominatim.test") as client:
def create_api_request_func_falcon(self):
- import nominatim.server.falcon.server
+ import nominatim_api.server.falcon.server
import falcon.testing
async def _request(endpoint, params, project_dir, environ, http_headers):
- app = nominatim.server.falcon.server.get_application(project_dir, environ)
+ app = nominatim_api.server.falcon.server.get_application(project_dir, environ)
async with falcon.testing.ASGIConductor(app) as conductor:
response = await conductor.get(f"/{endpoint}", params=params,
for k, v in context.http_headers.items():
env['HTTP_' + k.upper().replace('-', '_')] = v
- cmd = ['/usr/bin/env', 'php-cgi', '-f']
- if context.nominatim.code_coverage_path:
- env['XDEBUG_MODE'] = 'coverage'
- env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
- env['COV_PHP_DIR'] = context.nominatim.src_dir
- env['COV_TEST_NAME'] = f"{context.scenario.filename}:{context.scenario.line}"
- env['SCRIPT_FILENAME'] = \
- os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
- cmd.append(env['SCRIPT_FILENAME'])
- env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
- else:
- cmd.append(env['SCRIPT_FILENAME'])
+ cmd = ['/usr/bin/env', 'php-cgi', '-f', env['SCRIPT_FILENAME']]
for k,v in params.items():
cmd.append(f"{k}={v}")
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
import logging
from itertools import chain
-import psycopg2.extras
+import psycopg
+from psycopg import sql as pysql
from place_inserter import PlaceColumn
from table_compare import NominatimID, DBRow
-from nominatim.indexer import indexer
-from nominatim.tokenizer import factory as tokenizer_factory
+from nominatim_db.indexer import indexer
+from nominatim_db.tokenizer import factory as tokenizer_factory
def check_database_integrity(context):
""" Check some generic constraints on the tables.
"""
- with context.db.cursor() as cur:
+ with context.db.cursor(row_factory=psycopg.rows.tuple_row) as cur:
# place_addressline should not have duplicate (place_id, address_place_id)
cur.execute("""SELECT count(*) FROM
(SELECT place_id, address_place_id, count(*) as c
with context.db.cursor() as cur:
cur.execute("SELECT value FROM osm2pgsql_properties WHERE property = 'db_format'")
row = cur.fetchone()
- if row is None or row[0] == '1':
+ if row is None or row['value'] == '1':
for r in context.table:
last_node = 0
last_way = 0
cur.execute("""INSERT INTO planet_osm_rels (id, tags, members)
VALUES (%s, %s, %s)""",
- (r['id'], psycopg2.extras.Json(tags),
- psycopg2.extras.Json(members)))
+ (r['id'], psycopg.types.json.Json(tags),
+ psycopg.types.json.Json(members)))
@given("the ways")
def add_data_to_planet_ways(context):
with context.db.cursor() as cur:
cur.execute("SELECT value FROM osm2pgsql_properties WHERE property = 'db_format'")
row = cur.fetchone()
- json_tags = row is not None and row[0] != '1'
+ json_tags = row is not None and row['value'] != '1'
for r in context.table:
if json_tags:
- tags = psycopg2.extras.Json({h[5:]: r[h] for h in r.headings if h.startswith("tags+")})
+ tags = psycopg.types.json.Json({h[5:]: r[h] for h in r.headings if h.startswith("tags+")})
else:
tags = list(chain.from_iterable([(h[5:], r[h])
for h in r.headings if h.startswith("tags+")]))
expected rows are expected to be present with at least one database row.
When 'exactly' is given, there must not be additional rows in the database.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
expected_content = set()
for row in context.table:
nid = NominatimID(row['object'])
DBRow(nid, res, context).assert_row(row, ['object'])
if exact:
- cur.execute('SELECT osm_type, osm_id, class from {}'.format(table))
- actual = set([(r[0], r[1], r[2]) for r in cur])
+ cur.execute(pysql.SQL('SELECT osm_type, osm_id, class from')
+ + pysql.Identifier(table))
+ actual = set([(r['osm_type'], r['osm_id'], r['class']) for r in cur])
assert expected_content == actual, \
f"Missing entries: {expected_content - actual}\n" \
f"Not expected in table: {actual - expected_content}"
""" Ensure that no database row for the given object exists. The ID
must be of the form '<NRW><osm id>[:<class>]'.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
NominatimID(oid).query_osm_id(cur, "SELECT * FROM %s where {}" % table)
assert cur.rowcount == 0, \
"Found {} entries for ID {}".format(cur.rowcount, oid)
tokenizer = tokenizer_factory.get_tokenizer_for_db(context.nominatim.get_test_config())
with tokenizer.name_analyzer() as analyzer:
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
for row in context.table:
nid = NominatimID(row['object'])
nid.row_by_place_id(cur, 'search_name',
""" Check that there is noentry in the search_name table for the given
objects. IDs are in format '<NRW><osm id>[:<class>]'.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
NominatimID(oid).row_by_place_id(cur, 'search_name')
assert cur.rowcount == 0, \
All rows must be present as excepted and there must not be additional
rows.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
assert cur.rowcount == len(list(context.table)), \
"Postcode table has {} rows, expected {}.".format(cur.rowcount, len(list(context.table)))
plist.sort()
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
if nctx.tokenizer != 'legacy':
cur.execute("SELECT word FROM word WHERE type = 'P' and word = any(%s)",
(plist,))
and class = 'place' and type = 'postcode'""",
(plist,))
- found = [row[0] for row in cur]
+ found = [row['word'] for row in cur]
assert len(found) == len(set(found)), f"Duplicate rows for postcodes: {found}"
if exclude:
representing the addressee and the 'address' column, representing the
address item.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
for row in context.table:
nid = NominatimID(row['object'])
pid = nid.get_place_id(cur)
""" Check that the place_addressline doesn't contain any entries for the
given addressee/address item pairs.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
for row in context.table:
pid = NominatimID(row['object']).get_place_id(cur)
apid = NominatimID(row['address']).get_place_id(cur, allow_empty=True)
def check_location_property_osmline(context, oid, neg):
""" Check that the given way is present in the interpolation table.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
FROM location_property_osmline
WHERE osm_id = %s AND startnumber IS NOT NULL""",
expected rows are expected to be present with at least one database row.
When 'exactly' is given, there must not be additional rows in the database.
"""
- with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
+ with context.db.cursor() as cur:
expected_content = set()
for row in context.table:
if ':' in row['object']:
if exact:
cur.execute('SELECT osm_id, startnumber from location_property_osmline')
- actual = set([(r[0], r[1]) for r in cur])
+ actual = set([(r['osm_id'], r['startnumber']) for r in cur])
assert expected_content == actual, \
f"Missing entries: {expected_content - actual}\n" \
f"Not expected in table: {actual - expected_content}"
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
import tempfile
import random
import os
from pathlib import Path
-from nominatim.tools.exec_utils import run_osm2pgsql
-from nominatim.tools.replication import run_osm2pgsql_updates
+from nominatim_db.tools.exec_utils import run_osm2pgsql
+from nominatim_db.tools.replication import run_osm2pgsql_updates
from geometry_alias import ALIASES
def get_osm2pgsql_options(nominatim_env, fname, append):
return dict(import_file=fname,
- osm2pgsql=str(nominatim_env.build_dir / 'osm2pgsql' / 'osm2pgsql'),
+ osm2pgsql='osm2pgsql',
osm2pgsql_cache=50,
osm2pgsql_style=str(nominatim_env.get_test_config().get_import_style_file()),
osm2pgsql_style_path=nominatim_env.get_test_config().config_dir,
import re
import json
+import psycopg
+from psycopg import sql as pysql
+
from steps.check_functions import Almost
ID_REGEX = re.compile(r"(?P<typ>[NRW])(?P<oid>\d+)(:(?P<cls>\w+))?")
assert cur.rowcount == 1, \
"Place ID {!s} not unique. Found {} entries.".format(self, cur.rowcount)
- return cur.fetchone()[0]
+ return cur.fetchone()['place_id']
class DBRow:
def _has_centroid(self, expected):
if expected == 'in geometry':
- with self.context.db.cursor() as cur:
- cur.execute("""SELECT ST_Within(ST_SetSRID(ST_Point({cx}, {cy}), 4326),
- ST_SetSRID('{geomtxt}'::geometry, 4326))""".format(**self.db_row))
+ with self.context.db.cursor(row_factory=psycopg.rows.tuple_row) as cur:
+ cur.execute("""SELECT ST_Within(ST_SetSRID(ST_Point(%(cx)s, %(cy)s), 4326),
+ ST_SetSRID(%(geomtxt)s::geometry, 4326))""",
+ (self.db_row))
return cur.fetchone()[0]
if ' ' in expected:
def _has_geometry(self, expected):
geom = self.context.osm.parse_geometry(expected)
- with self.context.db.cursor() as cur:
- cur.execute("""SELECT ST_Equals(ST_SnapToGrid({}, 0.00001, 0.00001),
- ST_SnapToGrid(ST_SetSRID('{}'::geometry, 4326), 0.00001, 0.00001))""".format(
- geom, self.db_row['geomtxt']))
+ with self.context.db.cursor(row_factory=psycopg.rows.tuple_row) as cur:
+ cur.execute(pysql.SQL("""SELECT ST_Equals(ST_SnapToGrid({}, 0.00001, 0.00001),
+ ST_SnapToGrid(ST_SetSRID({}::geometry, 4326), 0.00001, 0.00001))""")
+ .format(pysql.SQL(geom),
+ pysql.Literal(self.db_row['geomtxt'])))
return cur.fetchone()[0]
def assert_msg(self, name, value):
if actual == 0:
return "place ID 0"
- with self.context.db.cursor() as cur:
+ with self.context.db.cursor(row_factory=psycopg.rows.tuple_row) as cur:
cur.execute("""SELECT osm_type, osm_id, class
FROM placex WHERE place_id = %s""",
(actual, ))
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Helper fixtures for API call tests.
import sqlalchemy as sa
-import nominatim.api as napi
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.api.search.query_analyzer_factory import make_query_analyzer
-from nominatim.tools import convert_sqlite
-import nominatim.api.logging as loglib
+import nominatim_api as napi
+from nominatim_db.db.sql_preprocessor import SQLPreprocessor
+from nominatim_api.search.query_analyzer_factory import make_query_analyzer
+from nominatim_db.tools import convert_sqlite
+import nominatim_api.logging as loglib
class APITester:
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Provides dummy implementations of ASGIAdaptor for testing.
"""
from collections import namedtuple
-import nominatim.api.v1.server_glue as glue
-from nominatim.config import Configuration
+import nominatim_api.v1.server_glue as glue
+from nominatim_api.config import Configuration
class FakeError(BaseException):
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for tokenized query data structures.
"""
import pytest
-from nominatim.api.search import query
+from nominatim_api.search import query
class MyToken(query.Token):
"""
import pytest
-from nominatim.api.search.query import Token, TokenRange, BreakType, PhraseType, TokenType, QueryStruct, Phrase
-from nominatim.api.search.db_search_builder import SearchBuilder
-from nominatim.api.search.token_assignment import TokenAssignment
-from nominatim.api.types import SearchDetails
-import nominatim.api.search.db_searches as dbs
+from nominatim_api.search.query import Token, TokenRange, BreakType, PhraseType, TokenType, QueryStruct, Phrase
+from nominatim_api.search.db_search_builder import SearchBuilder
+from nominatim_api.search.token_assignment import TokenAssignment
+from nominatim_api.types import SearchDetails
+import nominatim_api.search.db_searches as dbs
class MyToken(Token):
def get_category(self):
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for query analyzer for ICU tokenizer.
import pytest
import pytest_asyncio
-from nominatim.api import NominatimAPIAsync
-from nominatim.api.search.query import Phrase, PhraseType, TokenType, BreakType
-import nominatim.api.search.icu_tokenizer as tok
-from nominatim.api.logging import set_log_output, get_and_disable
+from nominatim_api import NominatimAPIAsync
+from nominatim_api.search.query import Phrase, PhraseType, TokenType, BreakType
+import nominatim_api.search.icu_tokenizer as tok
+from nominatim_api.logging import set_log_output, get_and_disable
async def add_word(conn, word_id, word_token, wtype, word, info = None):
t = conn.t.meta.tables['word']
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for query analyzer for legacy tokenizer.
import pytest
import pytest_asyncio
-from nominatim.api import NominatimAPIAsync
-from nominatim.api.search.query import Phrase, PhraseType, TokenType, BreakType
-import nominatim.api.search.legacy_tokenizer as tok
-from nominatim.api.logging import set_log_output, get_and_disable
+from nominatim_api import NominatimAPIAsync
+from nominatim_api.search.query import Phrase, PhraseType, TokenType, BreakType
+import nominatim_api.search.legacy_tokenizer as tok
+from nominatim_api.logging import set_log_output, get_and_disable
async def add_word(conn, word_id, word_token, word, count):
-
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test data types for search queries.
"""
import pytest
-import nominatim.api.search.query as nq
+import nominatim_api.search.query as nq
def test_token_range_equal():
assert nq.TokenRange(2, 3) == nq.TokenRange(2, 3)
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for query analyzer creation.
import pytest
-from nominatim.api import NominatimAPIAsync
-from nominatim.api.search.query_analyzer_factory import make_query_analyzer
-from nominatim.api.search.icu_tokenizer import ICUQueryAnalyzer
+from nominatim_api import NominatimAPIAsync
+from nominatim_api.search.query_analyzer_factory import make_query_analyzer
+from nominatim_api.search.icu_tokenizer import ICUQueryAnalyzer
@pytest.mark.asyncio
async def test_import_icu_tokenizer(table_factory):
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for running the country searcher.
"""
import pytest
-import nominatim.api as napi
-from nominatim.api.types import SearchDetails
-from nominatim.api.search.db_searches import CountrySearch
-from nominatim.api.search.db_search_fields import WeightedStrings
+import nominatim_api as napi
+from nominatim_api.types import SearchDetails
+from nominatim_api.search.db_searches import CountrySearch
+from nominatim_api.search.db_search_fields import WeightedStrings
def run_search(apiobj, frontend, global_penalty, ccodes,
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for running the near searcher.
"""
import pytest
-import nominatim.api as napi
-from nominatim.api.types import SearchDetails
-from nominatim.api.search.db_searches import NearSearch, PlaceSearch
-from nominatim.api.search.db_search_fields import WeightedStrings, WeightedCategories,\
+import nominatim_api as napi
+from nominatim_api.types import SearchDetails
+from nominatim_api.search.db_searches import NearSearch, PlaceSearch
+from nominatim_api.search.db_search_fields import WeightedStrings, WeightedCategories,\
FieldLookup, FieldRanking, RankedTokens
-from nominatim.api.search.db_search_lookups import LookupAll
+from nominatim_api.search.db_search_lookups import LookupAll
def run_search(apiobj, frontend, global_penalty, cat, cat_penalty=None, ccodes=[],
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for running the generic place searcher.
import pytest
-import nominatim.api as napi
-from nominatim.api.types import SearchDetails
-from nominatim.api.search.db_searches import PlaceSearch
-from nominatim.api.search.db_search_fields import WeightedStrings, WeightedCategories,\
+import nominatim_api as napi
+from nominatim_api.types import SearchDetails
+from nominatim_api.search.db_searches import PlaceSearch
+from nominatim_api.search.db_search_fields import WeightedStrings, WeightedCategories,\
FieldLookup, FieldRanking, RankedTokens
-from nominatim.api.search.db_search_lookups import LookupAll, LookupAny, Restrict
+from nominatim_api.search.db_search_lookups import LookupAll, LookupAny, Restrict
APIOPTIONS = ['search']
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for running the POI searcher.
"""
import pytest
-import nominatim.api as napi
-from nominatim.api.types import SearchDetails
-from nominatim.api.search.db_searches import PoiSearch
-from nominatim.api.search.db_search_fields import WeightedStrings, WeightedCategories
+import nominatim_api as napi
+from nominatim_api.types import SearchDetails
+from nominatim_api.search.db_searches import PoiSearch
+from nominatim_api.search.db_search_fields import WeightedStrings, WeightedCategories
def run_search(apiobj, frontend, global_penalty, poitypes, poi_penalties=None,
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for running the postcode searcher.
"""
import pytest
-import nominatim.api as napi
-from nominatim.api.types import SearchDetails
-from nominatim.api.search.db_searches import PostcodeSearch
-from nominatim.api.search.db_search_fields import WeightedStrings, FieldLookup, \
+import nominatim_api as napi
+from nominatim_api.types import SearchDetails
+from nominatim_api.search.db_searches import PostcodeSearch
+from nominatim_api.search.db_search_fields import WeightedStrings, FieldLookup, \
FieldRanking, RankedTokens
def run_search(apiobj, frontend, global_penalty, pcs, pc_penalties=None,
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for creation of token assignments from tokenized queries.
"""
import pytest
-from nominatim.api.search.query import QueryStruct, Phrase, PhraseType, BreakType, TokenType, TokenRange, Token
-from nominatim.api.search.token_assignment import yield_token_assignments, TokenAssignment, PENALTY_TOKENCHANGE
+from nominatim_api.search.query import QueryStruct, Phrase, PhraseType, BreakType, TokenType, TokenRange, Token
+from nominatim_api.search.token_assignment import yield_token_assignments, TokenAssignment, PENALTY_TOKENCHANGE
class MyToken(Token):
def get_category(self):
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for enhanced connection class for API functions.
import sqlalchemy as sa
-from nominatim.api import NominatimAPIAsync
+from nominatim_api import NominatimAPIAsync
@pytest_asyncio.fixture
async def apiobj(temp_db):
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the deletable v1 API call.
import pytest
import pytest_asyncio
-import psycopg2.extras
-
from fake_adaptor import FakeAdaptor, FakeError, FakeResponse
-import nominatim.api.v1.server_glue as glue
-import nominatim.api as napi
+import nominatim_api.v1.server_glue as glue
+import nominatim_api as napi
@pytest_asyncio.fixture
async def api():
@pytest.fixture(autouse=True)
def setup_deletable_table(self, temp_db_cursor, table_factory, temp_db_with_extensions):
- psycopg2.extras.register_hstore(temp_db_cursor)
table_factory('import_polygon_delete',
definition='osm_id bigint, osm_type char(1), class text, type text',
content=[(345, 'N', 'boundary', 'administrative'),
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for details API call.
import pytest
-import nominatim.api as napi
+import nominatim_api as napi
@pytest.mark.parametrize('idobj', (napi.PlaceID(332), napi.OsmID('W', 4),
napi.OsmID('W', 4, 'highway')))
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for lookup API call.
import pytest
-import nominatim.api as napi
+import nominatim_api as napi
def test_lookup_empty_list(apiobj, frontend):
api = frontend(apiobj, options={'details'})
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the deletable v1 API call.
import pytest
import pytest_asyncio
-import psycopg2.extras
-
from fake_adaptor import FakeAdaptor, FakeError, FakeResponse
-import nominatim.api.v1.server_glue as glue
-import nominatim.api as napi
+import nominatim_api.v1.server_glue as glue
+import nominatim_api as napi
@pytest_asyncio.fixture
async def api():
@pytest.fixture(autouse=True)
def setup_deletable_table(self, temp_db_cursor, table_factory, temp_db_with_extensions):
- psycopg2.extras.register_hstore(temp_db_cursor)
-
self.now = dt.datetime.now()
self.recent = dt.datetime.now() - dt.timedelta(days=3)
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for reverse API call.
import pytest
-import nominatim.api as napi
+import nominatim_api as napi
API_OPTIONS = {'reverse'}
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for search API calls.
import sqlalchemy as sa
-import nominatim.api as napi
-import nominatim.api.logging as loglib
+import nominatim_api as napi
+import nominatim_api.logging as loglib
API_OPTIONS = {'search'}
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the status API call.
import datetime as dt
import pytest
-from nominatim.version import NOMINATIM_VERSION, NominatimVersion
-import nominatim.api as napi
+from nominatim_db.version import NominatimVersion
+from nominatim_api.version import NOMINATIM_API_VERSION
+import nominatim_api as napi
def test_status_no_extra_info(apiobj, frontend):
api = frontend(apiobj)
assert result.status == 0
assert result.message == 'OK'
- assert result.software_version == NOMINATIM_VERSION
+ assert result.software_version == NOMINATIM_API_VERSION
assert result.database_version is None
assert result.data_updated is None
assert result.status == 0
assert result.message == 'OK'
- assert result.software_version == NOMINATIM_VERSION
- assert result.database_version == NominatimVersion(99, 5, 4, 2)
+ assert result.software_version == NOMINATIM_API_VERSION
+ assert result.database_version == '99.5.4-2'
assert result.data_updated == import_date
assert result.status == 700
assert result.message == 'Database connection failed'
- assert result.software_version == NOMINATIM_VERSION
+ assert result.software_version == NOMINATIM_API_VERSION
assert result.database_version is None
assert result.data_updated is None
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for loading of parameter dataclasses.
"""
import pytest
-from nominatim.errors import UsageError
-import nominatim.api.types as typ
+from nominatim_api.errors import UsageError
+import nominatim_api.types as typ
def test_no_params_defaults():
params = typ.LookupDetails.from_kwargs({})
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for export CLI function.
"""
import pytest
-import nominatim.cli
+import nominatim_db.cli
@pytest.fixture
def run_export(tmp_path, capsys):
def _exec(args):
- assert 0 == nominatim.cli.nominatim(module_dir='MODULE NOT AVAILABLE',
- osm2pgsql_path='OSM2PGSQL NOT AVAILABLE',
- cli_args=['export', '--project-dir', str(tmp_path)]
- + args)
+ assert 0 == nominatim_db.cli.nominatim(module_dir='MODULE NOT AVAILABLE',
+ osm2pgsql_path='OSM2PGSQL NOT AVAILABLE',
+ cli_args=['export', '--project-dir', str(tmp_path)]
+ + args)
return capsys.readouterr().out.split('\r\n')
return _exec
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the helper functions for v1 API.
"""
import pytest
-import nominatim.api.v1.helpers as helper
+import nominatim_api.v1.helpers as helper
@pytest.mark.parametrize('inp', ['',
'abc',
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test functions for adapting results to the user's locale.
"""
import pytest
-from nominatim.api import Locales
+from nominatim_api import Locales
def test_display_name_empty_names():
l = Locales(['en', 'de'])
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for formatting results for the V1 API.
import pytest
-import nominatim.api.v1 as api_impl
-import nominatim.api as napi
-from nominatim.version import NOMINATIM_VERSION
+import nominatim_api.v1 as api_impl
+import nominatim_api as napi
STATUS_FORMATS = {'text', 'json'}
result = api_impl.format_result(status, 'json', {})
- assert result == '{"status":700,"message":"Bad format.","software_version":"%s"}' % (NOMINATIM_VERSION, )
+ assert result == \
+ f'{{"status":700,"message":"Bad format.","software_version":"{napi.__version__}"}}'
def test_status_format_json_full():
result = api_impl.format_result(status, 'json', {})
- assert result == '{"status":0,"message":"OK","data_updated":"2010-02-07T20:20:03+00:00","software_version":"%s","database_version":"5.6"}' % (NOMINATIM_VERSION, )
+ assert result == \
+ f'{{"status":0,"message":"OK","data_updated":"2010-02-07T20:20:03+00:00","software_version":"{napi.__version__}","database_version":"5.6"}}'
# DetailedResult
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for formatting reverse results for the V1 API.
import pytest
-import nominatim.api.v1 as api_impl
-import nominatim.api as napi
+import nominatim_api.v1 as api_impl
+import nominatim_api as napi
FORMATS = ['json', 'jsonv2', 'geojson', 'geocodejson', 'xml']
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for result datatype helper functions.
import sqlalchemy as sa
-from nominatim.api import SourceTable, DetailedResult, Point
-import nominatim.api.results as nresults
+from nominatim_api import SourceTable, DetailedResult, Point
+import nominatim_api.results as nresults
def mkpoint(x, y):
return hexlify(struct.pack("=biidd", 1, 0x20000001, 4326, x, y)).decode('utf-8')
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the Python web frameworks adaptor, v1 API.
from fake_adaptor import FakeAdaptor, FakeError, FakeResponse
-import nominatim.api.v1.server_glue as glue
-import nominatim.api as napi
-import nominatim.api.logging as loglib
+import nominatim_api.v1.server_glue as glue
+import nominatim_api as napi
+import nominatim_api.logging as loglib
# ASGIAdaptor.get_int/bool()
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for warm-up CLI function.
"""
import pytest
-import nominatim.cli
+import nominatim_db.cli
@pytest.fixture(autouse=True)
def setup_database_with_context(apiobj, table_factory):
@pytest.mark.parametrize('args', [['--search-only'], ['--reverse-only']])
def test_warm_all(tmp_path, args):
- assert 0 == nominatim.cli.nominatim(module_dir='MODULE NOT AVAILABLE',
- osm2pgsql_path='OSM2PGSQL NOT AVAILABLE',
- cli_args=['admin', '--project-dir', str(tmp_path),
- '--warm'] + args)
+ assert 0 == nominatim_db.cli.nominatim(module_dir='MODULE NOT AVAILABLE',
+ osm2pgsql_path='OSM2PGSQL NOT AVAILABLE',
+ cli_args=['admin', '--project-dir', str(tmp_path),
+ '--warm'] + args)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
import pytest
-import nominatim.cli
+import nominatim_db.cli
class MockParamCapture:
""" Mock that records the parameters with which a function was called
return self.return_value
+class AsyncMockParamCapture:
+ """ Mock that records the parameters with which a function was called
+ as well as the number of calls.
+ """
+ def __init__(self, retval=0):
+ self.called = 0
+ self.return_value = retval
+ self.last_args = None
+ self.last_kwargs = None
+
+ async def __call__(self, *args, **kwargs):
+ self.called += 1
+ self.last_args = args
+ self.last_kwargs = kwargs
+ return self.return_value
+
+
class DummyTokenizer:
def __init__(self, *args, **kwargs):
self.update_sql_functions_called = False
Returns a function that can be called with the desired CLI arguments.
"""
def _call_nominatim(*args):
- return nominatim.cli.nominatim(module_dir='MODULE NOT AVAILABLE',
- osm2pgsql_path='OSM2PGSQL NOT AVAILABLE',
- cli_args=args)
+ return nominatim_db.cli.nominatim(module_dir='MODULE NOT AVAILABLE',
+ osm2pgsql_path='OSM2PGSQL NOT AVAILABLE',
+ cli_args=args)
return _call_nominatim
return get_mock
+@pytest.fixture
+def async_mock_func_factory(monkeypatch):
+ def get_mock(module, func):
+ mock = AsyncMockParamCapture()
+ mock.func_name = func
+ monkeypatch.setattr(module, func, mock)
+ return mock
+
+ return get_mock
+
+
@pytest.fixture
def cli_tokenizer_mock(monkeypatch):
tok = DummyTokenizer()
- monkeypatch.setattr(nominatim.tokenizer.factory, 'get_tokenizer_for_db',
+ monkeypatch.setattr(nominatim_db.tokenizer.factory, 'get_tokenizer_for_db',
lambda *args: tok)
- monkeypatch.setattr(nominatim.tokenizer.factory, 'create_tokenizer',
+ monkeypatch.setattr(nominatim_db.tokenizer.factory, 'create_tokenizer',
lambda *args: tok)
return tok
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for command line interface wrapper.
import importlib
import pytest
-import nominatim.indexer.indexer
-import nominatim.tools.add_osm_data
-import nominatim.tools.freeze
+import nominatim_db.indexer.indexer
+import nominatim_db.tools.add_osm_data
+import nominatim_db.tools.freeze
+import nominatim_db.tools.tiger_data
def test_cli_help(cli_call, capsys):
captured = capsys.readouterr()
assert captured.out.startswith('Nominatim version')
-@pytest.mark.parametrize("name,oid", [('file', 'foo.osm'), ('diff', 'foo.osc')])
-def test_cli_add_data_file_command(cli_call, mock_func_factory, name, oid):
- mock_run_legacy = mock_func_factory(nominatim.tools.add_osm_data, 'add_data_from_file')
- assert cli_call('add-data', '--' + name, str(oid)) == 0
-
- assert mock_run_legacy.called == 1
-
-
-@pytest.mark.parametrize("name,oid", [('node', 12), ('way', 8), ('relation', 32)])
-def test_cli_add_data_object_command(cli_call, mock_func_factory, name, oid):
- mock_run_legacy = mock_func_factory(nominatim.tools.add_osm_data, 'add_osm_object')
- assert cli_call('add-data', '--' + name, str(oid)) == 0
-
- assert mock_run_legacy.called == 1
-
-
-
-def test_cli_add_data_tiger_data(cli_call, cli_tokenizer_mock, mock_func_factory):
- mock = mock_func_factory(nominatim.tools.tiger_data, 'add_tiger_data')
-
- assert cli_call('add-data', '--tiger-data', 'somewhere') == 0
-
- assert mock.called == 1
-
def test_cli_serve_php(cli_call, mock_func_factory):
- func = mock_func_factory(nominatim.cli, 'run_php_server')
+ func = mock_func_factory(nominatim_db.cli, 'run_php_server')
cli_call('serve', '--engine', 'php') == 0
assert func.called == 1
-def test_cli_serve_starlette_custom_server(cli_call, mock_func_factory):
- pytest.importorskip("starlette")
- mod = pytest.importorskip("uvicorn")
- func = mock_func_factory(mod, "run")
- cli_call('serve', '--engine', 'starlette', '--server', 'foobar:4545') == 0
+class TestCliWithDb:
- assert func.called == 1
- assert func.last_kwargs['host'] == 'foobar'
- assert func.last_kwargs['port'] == 4545
+ @pytest.fixture(autouse=True)
+ def setup_cli_call(self, cli_call, temp_db, cli_tokenizer_mock, table_factory):
+ self.call_nominatim = cli_call
+ self.tokenizer_mock = cli_tokenizer_mock
+ # Make sure tools.freeze.is_frozen doesn't report database as frozen. Monkeypatching failed
+ table_factory('place')
-def test_cli_serve_starlette_custom_server_bad_port(cli_call, mock_func_factory):
- pytest.importorskip("starlette")
- mod = pytest.importorskip("uvicorn")
- func = mock_func_factory(mod, "run")
+ @pytest.mark.parametrize("name,oid", [('file', 'foo.osm'), ('diff', 'foo.osc')])
+ def test_cli_add_data_file_command(self, cli_call, mock_func_factory, name, oid):
+ mock_run_legacy = mock_func_factory(nominatim_db.tools.add_osm_data, 'add_data_from_file')
+ assert cli_call('add-data', '--' + name, str(oid)) == 0
- cli_call('serve', '--engine', 'starlette', '--server', 'foobar:45:45') == 1
+ assert mock_run_legacy.called == 1
-@pytest.mark.parametrize("engine", ['falcon', 'starlette'])
-def test_cli_serve_uvicorn_based(cli_call, engine, mock_func_factory):
- pytest.importorskip(engine)
- mod = pytest.importorskip("uvicorn")
- func = mock_func_factory(mod, "run")
+ @pytest.mark.parametrize("name,oid", [('node', 12), ('way', 8), ('relation', 32)])
+ def test_cli_add_data_object_command(self, cli_call, mock_func_factory, name, oid):
+ mock_run_legacy = mock_func_factory(nominatim_db.tools.add_osm_data, 'add_osm_object')
+ assert cli_call('add-data', '--' + name, str(oid)) == 0
- cli_call('serve', '--engine', engine) == 0
+ assert mock_run_legacy.called == 1
- assert func.called == 1
- assert func.last_kwargs['host'] == '127.0.0.1'
- assert func.last_kwargs['port'] == 8088
-class TestCliWithDb:
+ def test_cli_add_data_tiger_data(self, cli_call, cli_tokenizer_mock, async_mock_func_factory):
+ mock = async_mock_func_factory(nominatim_db.tools.tiger_data, 'add_tiger_data')
- @pytest.fixture(autouse=True)
- def setup_cli_call(self, cli_call, temp_db, cli_tokenizer_mock):
- self.call_nominatim = cli_call
- self.tokenizer_mock = cli_tokenizer_mock
+ assert cli_call('add-data', '--tiger-data', 'somewhere') == 0
+ assert mock.called == 1
def test_freeze_command(self, mock_func_factory):
- mock_drop = mock_func_factory(nominatim.tools.freeze, 'drop_update_tables')
- mock_flatnode = mock_func_factory(nominatim.tools.freeze, 'drop_flatnode_file')
+ mock_drop = mock_func_factory(nominatim_db.tools.freeze, 'drop_update_tables')
+ mock_flatnode = mock_func_factory(nominatim_db.tools.freeze, 'drop_flatnode_file')
assert self.call_nominatim('freeze') == 0
@pytest.mark.parametrize("params,do_bnds,do_ranks", [
- ([], 1, 1),
- (['--boundaries-only'], 1, 0),
- (['--no-boundaries'], 0, 1),
+ ([], 2, 2),
+ (['--boundaries-only'], 2, 0),
+ (['--no-boundaries'], 0, 2),
(['--boundaries-only', '--no-boundaries'], 0, 0)])
- def test_index_command(self, mock_func_factory, table_factory,
+ def test_index_command(self, monkeypatch, async_mock_func_factory, table_factory,
params, do_bnds, do_ranks):
table_factory('import_status', 'indexed bool')
- bnd_mock = mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_boundaries')
- rank_mock = mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_by_rank')
- postcode_mock = mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_postcodes')
+ bnd_mock = async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_boundaries')
+ rank_mock = async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_by_rank')
+ postcode_mock = async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_postcodes')
+
+ monkeypatch.setattr(nominatim_db.indexer.indexer.Indexer, 'has_pending',
+ [False, True].pop)
assert self.call_nominatim('index', *params) == 0
def test_special_phrases_wiki_command(self, mock_func_factory):
- func = mock_func_factory(nominatim.clicmd.special_phrases.SPImporter, 'import_phrases')
+ func = mock_func_factory(nominatim_db.clicmd.special_phrases.SPImporter, 'import_phrases')
self.call_nominatim('special-phrases', '--import-from-wiki', '--no-replace')
def test_special_phrases_csv_command(self, src_dir, mock_func_factory):
- func = mock_func_factory(nominatim.clicmd.special_phrases.SPImporter, 'import_phrases')
+ func = mock_func_factory(nominatim_db.clicmd.special_phrases.SPImporter, 'import_phrases')
testdata = src_dir / 'test' / 'testdb'
csv_path = str((testdata / 'full_en_phrases_test.csv').resolve())
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for the command line interface wrapper admin subcommand.
"""
import pytest
-import nominatim.tools.admin
-import nominatim.tools.check_database
-import nominatim.tools.migration
-import nominatim.clicmd.admin
+import nominatim_db.tools.admin
+import nominatim_db.tools.check_database
+import nominatim_db.tools.migration
+import nominatim_db.clicmd.admin
def test_admin_command_check_database(cli_call, mock_func_factory):
- mock = mock_func_factory(nominatim.tools.check_database, 'check_database')
+ mock = mock_func_factory(nominatim_db.tools.check_database, 'check_database')
assert cli_call('admin', '--check-database') == 0
assert mock.called == 1
def test_admin_migrate(cli_call, mock_func_factory):
- mock = mock_func_factory(nominatim.tools.migration, 'migrate')
+ mock = mock_func_factory(nominatim_db.tools.migration, 'migrate')
assert cli_call('admin', '--migrate') == 0
assert mock.called == 1
def test_admin_clean_deleted_relations(cli_call, mock_func_factory):
- mock = mock_func_factory(nominatim.tools.admin, 'clean_deleted_relations')
+ mock = mock_func_factory(nominatim_db.tools.admin, 'clean_deleted_relations')
assert cli_call('admin', '--clean-deleted', '1 month') == 0
assert mock.called == 1
def test_admin_clean_deleted_relations_no_age(cli_call, mock_func_factory):
- mock = mock_func_factory(nominatim.tools.admin, 'clean_deleted_relations')
+ mock = mock_func_factory(nominatim_db.tools.admin, 'clean_deleted_relations')
assert cli_call('admin', '--clean-deleted') == 1
@pytest.mark.parametrize("func, params", [('analyse_indexing', ('--analyse-indexing', ))])
def test_analyse_indexing(self, mock_func_factory, func, params):
- mock = mock_func_factory(nominatim.tools.admin, func)
+ mock = mock_func_factory(nominatim_db.tools.admin, func)
assert self.call_nominatim('admin', *params) == 0
assert mock.called == 1
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for API access commands of command-line interface wrapper.
import json
import pytest
-import nominatim.clicmd.api
-import nominatim.api as napi
+import nominatim_db.clicmd.api
+import nominatim_api as napi
class TestCliStatusCall:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-2.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for import command of the command-line interface wrapper.
"""
import pytest
-import nominatim.tools.database_import
-import nominatim.data.country_info
-import nominatim.tools.refresh
-import nominatim.tools.postcodes
-import nominatim.indexer.indexer
-import nominatim.db.properties
+import nominatim_db.tools.database_import
+import nominatim_db.data.country_info
+import nominatim_db.tools.refresh
+import nominatim_db.tools.postcodes
+import nominatim_db.indexer.indexer
+import nominatim_db.db.properties
class TestCliImportWithDb:
@pytest.mark.parametrize('with_updates', [True, False])
- def test_import_full(self, mock_func_factory, with_updates, place_table, property_table):
+ def test_import_full(self, mock_func_factory, async_mock_func_factory,
+ with_updates, place_table, property_table):
mocks = [
- mock_func_factory(nominatim.tools.database_import, 'setup_database_skeleton'),
- mock_func_factory(nominatim.data.country_info, 'setup_country_tables'),
- mock_func_factory(nominatim.tools.database_import, 'import_osm_data'),
- mock_func_factory(nominatim.tools.refresh, 'import_wikipedia_articles'),
- mock_func_factory(nominatim.tools.refresh, 'import_secondary_importance'),
- mock_func_factory(nominatim.tools.database_import, 'truncate_data_tables'),
- mock_func_factory(nominatim.tools.database_import, 'load_data'),
- mock_func_factory(nominatim.tools.database_import, 'create_tables'),
- mock_func_factory(nominatim.tools.database_import, 'create_table_triggers'),
- mock_func_factory(nominatim.tools.database_import, 'create_partition_tables'),
- mock_func_factory(nominatim.tools.database_import, 'create_search_indices'),
- mock_func_factory(nominatim.data.country_info, 'create_country_names'),
- mock_func_factory(nominatim.tools.refresh, 'load_address_levels_from_config'),
- mock_func_factory(nominatim.tools.postcodes, 'update_postcodes'),
- mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_full'),
- mock_func_factory(nominatim.tools.refresh, 'setup_website'),
+ mock_func_factory(nominatim_db.tools.database_import, 'setup_database_skeleton'),
+ mock_func_factory(nominatim_db.data.country_info, 'setup_country_tables'),
+ mock_func_factory(nominatim_db.tools.database_import, 'import_osm_data'),
+ mock_func_factory(nominatim_db.tools.refresh, 'import_wikipedia_articles'),
+ mock_func_factory(nominatim_db.tools.refresh, 'import_secondary_importance'),
+ mock_func_factory(nominatim_db.tools.database_import, 'truncate_data_tables'),
+ async_mock_func_factory(nominatim_db.tools.database_import, 'load_data'),
+ mock_func_factory(nominatim_db.tools.database_import, 'create_tables'),
+ mock_func_factory(nominatim_db.tools.database_import, 'create_table_triggers'),
+ mock_func_factory(nominatim_db.tools.database_import, 'create_partition_tables'),
+ async_mock_func_factory(nominatim_db.tools.database_import, 'create_search_indices'),
+ mock_func_factory(nominatim_db.data.country_info, 'create_country_names'),
+ mock_func_factory(nominatim_db.tools.refresh, 'load_address_levels_from_config'),
+ mock_func_factory(nominatim_db.tools.postcodes, 'update_postcodes'),
+ async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_full'),
+ mock_func_factory(nominatim_db.tools.refresh, 'setup_website'),
]
params = ['import', '--osm-file', __file__]
if with_updates:
- mocks.append(mock_func_factory(nominatim.tools.freeze, 'drop_update_tables'))
+ mocks.append(mock_func_factory(nominatim_db.tools.freeze, 'drop_update_tables'))
params.append('--no-updates')
- cf_mock = mock_func_factory(nominatim.tools.refresh, 'create_functions')
+ cf_mock = mock_func_factory(nominatim_db.tools.refresh, 'create_functions')
assert self.call_nominatim(*params) == 0
assert mock.called == 1, "Mock '{}' not called".format(mock.func_name)
- def test_import_continue_load_data(self, mock_func_factory):
+ def test_import_continue_load_data(self, mock_func_factory, async_mock_func_factory):
mocks = [
- mock_func_factory(nominatim.tools.database_import, 'truncate_data_tables'),
- mock_func_factory(nominatim.tools.database_import, 'load_data'),
- mock_func_factory(nominatim.tools.database_import, 'create_search_indices'),
- mock_func_factory(nominatim.data.country_info, 'create_country_names'),
- mock_func_factory(nominatim.tools.postcodes, 'update_postcodes'),
- mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_full'),
- mock_func_factory(nominatim.tools.refresh, 'setup_website'),
- mock_func_factory(nominatim.db.properties, 'set_property')
+ mock_func_factory(nominatim_db.tools.database_import, 'truncate_data_tables'),
+ async_mock_func_factory(nominatim_db.tools.database_import, 'load_data'),
+ async_mock_func_factory(nominatim_db.tools.database_import, 'create_search_indices'),
+ mock_func_factory(nominatim_db.data.country_info, 'create_country_names'),
+ mock_func_factory(nominatim_db.tools.postcodes, 'update_postcodes'),
+ async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_full'),
+ mock_func_factory(nominatim_db.tools.refresh, 'setup_website'),
+ mock_func_factory(nominatim_db.db.properties, 'set_property')
]
assert self.call_nominatim('import', '--continue', 'load-data') == 0
assert mock.called == 1, "Mock '{}' not called".format(mock.func_name)
- def test_import_continue_indexing(self, mock_func_factory, placex_table,
- temp_db_conn):
+ def test_import_continue_indexing(self, mock_func_factory, async_mock_func_factory,
+ placex_table, temp_db_conn):
mocks = [
- mock_func_factory(nominatim.tools.database_import, 'create_search_indices'),
- mock_func_factory(nominatim.data.country_info, 'create_country_names'),
- mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_full'),
- mock_func_factory(nominatim.tools.refresh, 'setup_website'),
- mock_func_factory(nominatim.db.properties, 'set_property')
+ async_mock_func_factory(nominatim_db.tools.database_import, 'create_search_indices'),
+ mock_func_factory(nominatim_db.data.country_info, 'create_country_names'),
+ async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_full'),
+ mock_func_factory(nominatim_db.tools.refresh, 'setup_website'),
+ mock_func_factory(nominatim_db.db.properties, 'set_property')
]
assert self.call_nominatim('import', '--continue', 'indexing') == 0
assert self.call_nominatim('import', '--continue', 'indexing') == 0
- def test_import_continue_postprocess(self, mock_func_factory):
+ def test_import_continue_postprocess(self, mock_func_factory, async_mock_func_factory):
mocks = [
- mock_func_factory(nominatim.tools.database_import, 'create_search_indices'),
- mock_func_factory(nominatim.data.country_info, 'create_country_names'),
- mock_func_factory(nominatim.tools.refresh, 'setup_website'),
- mock_func_factory(nominatim.db.properties, 'set_property')
+ async_mock_func_factory(nominatim_db.tools.database_import, 'create_search_indices'),
+ mock_func_factory(nominatim_db.data.country_info, 'create_country_names'),
+ mock_func_factory(nominatim_db.tools.refresh, 'setup_website'),
+ mock_func_factory(nominatim_db.db.properties, 'set_property')
]
assert self.call_nominatim('import', '--continue', 'db-postprocess') == 0
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for command line interface wrapper for refresk command.
"""
import pytest
-import nominatim.tools.refresh
-import nominatim.tools.postcodes
-import nominatim.indexer.indexer
+import nominatim_db.tools.refresh
+import nominatim_db.tools.postcodes
+import nominatim_db.indexer.indexer
class TestRefresh:
('website', 'setup_website'),
])
def test_refresh_command(self, mock_func_factory, command, func):
- mock_func_factory(nominatim.tools.refresh, 'create_functions')
- func_mock = mock_func_factory(nominatim.tools.refresh, func)
+ mock_func_factory(nominatim_db.tools.refresh, 'create_functions')
+ func_mock = mock_func_factory(nominatim_db.tools.refresh, func)
assert self.call_nominatim('refresh', '--' + command) == 0
assert func_mock.called == 1
assert self.tokenizer_mock.update_word_tokens_called
- def test_refresh_postcodes(self, mock_func_factory, place_table):
- func_mock = mock_func_factory(nominatim.tools.postcodes, 'update_postcodes')
- idx_mock = mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_postcodes')
+ def test_refresh_postcodes(self, async_mock_func_factory, mock_func_factory, place_table):
+ func_mock = mock_func_factory(nominatim_db.tools.postcodes, 'update_postcodes')
+ idx_mock = async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_postcodes')
assert self.call_nominatim('refresh', '--postcodes') == 0
assert func_mock.called == 1
def test_refresh_create_functions(self, mock_func_factory):
- func_mock = mock_func_factory(nominatim.tools.refresh, 'create_functions')
+ func_mock = mock_func_factory(nominatim_db.tools.refresh, 'create_functions')
assert self.call_nominatim('refresh', '--functions') == 0
assert func_mock.called == 1
def test_refresh_secondary_importance_new_table(self, mock_func_factory):
- mocks = [mock_func_factory(nominatim.tools.refresh, 'import_secondary_importance'),
- mock_func_factory(nominatim.tools.refresh, 'create_functions')]
+ mocks = [mock_func_factory(nominatim_db.tools.refresh, 'import_secondary_importance'),
+ mock_func_factory(nominatim_db.tools.refresh, 'create_functions')]
assert self.call_nominatim('refresh', '--secondary-importance') == 0
assert mocks[0].called == 1
def test_refresh_importance_computed_after_wiki_import(self, monkeypatch, mock_func_factory):
calls = []
- monkeypatch.setattr(nominatim.tools.refresh, 'import_wikipedia_articles',
+ monkeypatch.setattr(nominatim_db.tools.refresh, 'import_wikipedia_articles',
lambda *args, **kwargs: calls.append('import') or 0)
- monkeypatch.setattr(nominatim.tools.refresh, 'recompute_importance',
+ monkeypatch.setattr(nominatim_db.tools.refresh, 'recompute_importance',
lambda *args, **kwargs: calls.append('update'))
- func_mock = mock_func_factory(nominatim.tools.refresh, 'create_functions')
+ func_mock = mock_func_factory(nominatim_db.tools.refresh, 'create_functions')
assert self.call_nominatim('refresh', '--importance', '--wiki-data') == 0
('--data-area', 'r7723', '--data-area', 'r2'),
('--data-area', 'R9284425', '--data-object', 'n1234567894567')])
def test_refresh_objects(self, params, mock_func_factory):
- func_mock = mock_func_factory(nominatim.tools.refresh, 'invalidate_osm_object')
+ func_mock = mock_func_factory(nominatim_db.tools.refresh, 'invalidate_osm_object')
assert self.call_nominatim('refresh', *params) == 0
@pytest.mark.parametrize('func', ('--data-object', '--data-area'))
@pytest.mark.parametrize('param', ('234', 'a55', 'R 453', 'Rel'))
def test_refresh_objects_bad_param(self, func, param, mock_func_factory):
- func_mock = mock_func_factory(nominatim.tools.refresh, 'invalidate_osm_object')
+ func_mock = mock_func_factory(nominatim_db.tools.refresh, 'invalidate_osm_object')
self.call_nominatim('refresh', func, param) == 1
assert func_mock.called == 0
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2023 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for replication command of command-line interface wrapper.
import pytest
-import nominatim.cli
-import nominatim.indexer.indexer
-import nominatim.tools.replication
-import nominatim.tools.refresh
-from nominatim.db import status
+import nominatim_db.cli
+import nominatim_db.indexer.indexer
+import nominatim_db.tools.replication
+import nominatim_db.tools.refresh
+from nominatim_db.db import status
@pytest.fixture
def tokenizer_mock(monkeypatch):
self.finalize_import_called = True
tok = DummyTokenizer()
- monkeypatch.setattr(nominatim.tokenizer.factory, 'get_tokenizer_for_db',
+ monkeypatch.setattr(nominatim_db.tokenizer.factory, 'get_tokenizer_for_db',
lambda *args: tok)
- monkeypatch.setattr(nominatim.tokenizer.factory, 'create_tokenizer',
+ monkeypatch.setattr(nominatim_db.tokenizer.factory, 'create_tokenizer',
lambda *args: tok)
return tok
@pytest.fixture
-def index_mock(mock_func_factory, tokenizer_mock, init_status):
- return mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_full')
+def index_mock(async_mock_func_factory, tokenizer_mock, init_status):
+ return async_mock_func_factory(nominatim_db.indexer.indexer.Indexer, 'index_full')
@pytest.fixture
def update_mock(mock_func_factory, init_status, tokenizer_mock):
- return mock_func_factory(nominatim.tools.replication, 'update')
+ return mock_func_factory(nominatim_db.tools.replication, 'update')
class TestCliReplication:
@pytest.fixture(autouse=True)
def setup_update_function(self, monkeypatch):
def _mock_updates(states):
- monkeypatch.setattr(nominatim.tools.replication, 'update',
+ monkeypatch.setattr(nominatim_db.tools.replication, 'update',
lambda *args, **kwargs: states.pop())
self.update_states = _mock_updates
(('--check-for-updates',), 'check_for_updates')
])
def test_replication_command(self, mock_func_factory, params, func):
- func_mock = mock_func_factory(nominatim.tools.replication, func)
+ func_mock = mock_func_factory(nominatim_db.tools.replication, func)
if params == ('--init',):
- umock = mock_func_factory(nominatim.tools.refresh, 'create_functions')
+ umock = mock_func_factory(nominatim_db.tools.refresh, 'create_functions')
assert self.call_nominatim(*params) == 0
assert func_mock.called == 1
@pytest.mark.parametrize("update_interval", [60, 3600])
def test_replication_catchup(self, placex_table, monkeypatch, index_mock, update_interval):
monkeypatch.setenv('NOMINATIM_REPLICATION_UPDATE_INTERVAL', str(update_interval))
- self.update_states([nominatim.tools.replication.UpdateState.NO_CHANGES])
+ self.update_states([nominatim_db.tools.replication.UpdateState.NO_CHANGES])
assert self.call_nominatim('--catch-up') == 0
def test_replication_update_continuous(self, index_mock):
- self.update_states([nominatim.tools.replication.UpdateState.UP_TO_DATE,
- nominatim.tools.replication.UpdateState.UP_TO_DATE])
+ self.update_states([nominatim_db.tools.replication.UpdateState.UP_TO_DATE,
+ nominatim_db.tools.replication.UpdateState.UP_TO_DATE])
with pytest.raises(IndexError):
self.call_nominatim()
def test_replication_update_continuous_no_change(self, mock_func_factory,
index_mock):
- self.update_states([nominatim.tools.replication.UpdateState.NO_CHANGES,
- nominatim.tools.replication.UpdateState.UP_TO_DATE])
+ self.update_states([nominatim_db.tools.replication.UpdateState.NO_CHANGES,
+ nominatim_db.tools.replication.UpdateState.UP_TO_DATE])
sleep_mock = mock_func_factory(time, 'sleep')
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for loading dotenv configuration.
from pathlib import Path
import pytest
-from nominatim.config import Configuration, flatten_config_list
-from nominatim.errors import UsageError
+from nominatim_db.config import Configuration, flatten_config_list
+from nominatim_db.errors import UsageError
@pytest.fixture
def make_config():
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for loading extra Python modules.
import pytest
-from nominatim.config import Configuration
+from nominatim_db.config import Configuration
@pytest.fixture
def test_config(src_dir, tmp_path):
def test_load_default_module(test_config):
- module = test_config.load_plugin_module('version', 'nominatim')
+ module = test_config.load_plugin_module('version', 'nominatim_db')
assert isinstance(module.NOMINATIM_VERSION, tuple)
def test_load_default_module_with_hyphen(test_config):
- module = test_config.load_plugin_module('place-info', 'nominatim.data')
+ module = test_config.load_plugin_module('place-info', 'nominatim_db.data')
assert isinstance(module.PlaceInfo, object)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
import itertools
import sys
from pathlib import Path
-import psycopg2
+import psycopg
+from psycopg import sql as pysql
import pytest
# always test against the source
SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
-sys.path.insert(0, str(SRC_DIR))
+sys.path.insert(0, str(SRC_DIR / 'src'))
-from nominatim.config import Configuration
-from nominatim.db import connection
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-import nominatim.tokenizer.factory
+from nominatim_db.config import Configuration
+from nominatim_db.db import connection
+from nominatim_db.db.sql_preprocessor import SQLPreprocessor
+import nominatim_db.tokenizer.factory
import dummy_tokenizer
import mocks
exported into NOMINATIM_DATABASE_DSN.
"""
name = 'test_nominatim_python_unittest'
- conn = psycopg2.connect(database='postgres')
- conn.set_isolation_level(0)
- with conn.cursor() as cur:
- cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
- cur.execute('CREATE DATABASE {}'.format(name))
-
- conn.close()
+ with psycopg.connect(dbname='postgres', autocommit=True) as conn:
+ with conn.cursor() as cur:
+ cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
+ cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
- yield name
-
- conn = psycopg2.connect(database='postgres')
+ with psycopg.connect(dbname=name) as conn:
+ with conn.cursor() as cur:
+ cur.execute('CREATE EXTENSION hstore')
- conn.set_isolation_level(0)
- with conn.cursor() as cur:
- cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
+ yield name
- conn.close()
+ with psycopg.connect(dbname='postgres', autocommit=True) as conn:
+ with conn.cursor() as cur:
+ cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
@pytest.fixture
@pytest.fixture
def temp_db_with_extensions(temp_db):
- conn = psycopg2.connect(database=temp_db)
- with conn.cursor() as cur:
- cur.execute('CREATE EXTENSION hstore; CREATE EXTENSION postgis;')
- conn.commit()
- conn.close()
+ with psycopg.connect(dbname=temp_db) as conn:
+ with conn.cursor() as cur:
+ cur.execute('CREATE EXTENSION postgis')
return temp_db
def temp_db_conn(temp_db):
""" Connection to the test database.
"""
- with connection.connect('dbname=' + temp_db) as conn:
+ with connection.connect('', autocommit=True, dbname=temp_db) as conn:
+ connection.register_hstore(conn)
yield conn
""" Connection and cursor towards the test database. The connection will
be in auto-commit mode.
"""
- conn = psycopg2.connect('dbname=' + temp_db)
- conn.set_isolation_level(0)
- with conn.cursor(cursor_factory=CursorForTesting) as cur:
- yield cur
- conn.close()
+ with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
+ connection.register_hstore(conn)
+ with conn.cursor() as cur:
+ yield cur
@pytest.fixture
-def table_factory(temp_db_cursor):
+def table_factory(temp_db_conn):
""" A fixture that creates new SQL tables, potentially filled with
content.
"""
def mk_table(name, definition='id INT', content=None):
- temp_db_cursor.execute('CREATE TABLE {} ({})'.format(name, definition))
- if content is not None:
- temp_db_cursor.execute_values("INSERT INTO {} VALUES %s".format(name), content)
+ with psycopg.ClientCursor(temp_db_conn) as cur:
+ cur.execute('CREATE TABLE {} ({})'.format(name, definition))
+ if content:
+ sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
+ .format(pysql.Identifier(name),
+ pysql.SQL(',').join([pysql.Placeholder() for _ in range(len(content[0]))]))
+ cur.executemany(sql , content)
return mk_table
""" A factory for rows in the place table. The table is created as a
prerequisite to the fixture.
"""
- psycopg2.extras.register_hstore(temp_db_cursor)
idseq = itertools.count(1001)
def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
admin_level=None, address=None, extratags=None, geom=None):
def _import_dummy(*args, **kwargs):
return dummy_tokenizer
- monkeypatch.setattr(nominatim.tokenizer.factory, "_import_tokenizer", _import_dummy)
+ monkeypatch.setattr(nominatim_db.tokenizer.factory,
+ "_import_tokenizer", _import_dummy)
property_table.set('tokenizer', 'dummy')
def _create_tokenizer():
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
-Specialised psycopg2 cursor with shortcut functions useful for testing.
+Specialised psycopg cursor with shortcut functions useful for testing.
"""
-import psycopg2.extras
+import psycopg
-class CursorForTesting(psycopg2.extras.DictCursor):
+class CursorForTesting(psycopg.Cursor):
""" Extension to the DictCursor class that provides execution
short-cuts that simplify writing assertions.
"""
return self.scalar('SELECT count(*) FROM ' + table)
return self.scalar('SELECT count(*) FROM {} WHERE {}'.format(table, where))
-
-
- def execute_values(self, *args, **kwargs):
- """ Execute the execute_values() function on the cursor.
- """
- psycopg2.extras.execute_values(self, *args, **kwargs)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for function that handle country properties.
from textwrap import dedent
import pytest
-from nominatim.data import country_info
+from nominatim_db.data import country_info
@pytest.fixture
def loaded_country(def_config):
+++ /dev/null
-# SPDX-License-Identifier: GPL-2.0-only
-#
-# This file is part of Nominatim. (https://nominatim.org)
-#
-# Copyright (C) 2022 by the Nominatim developer community.
-# For a full list of authors see the git log.
-"""
-Tests for function providing a non-blocking query interface towards PostgreSQL.
-"""
-from contextlib import closing
-import concurrent.futures
-
-import pytest
-import psycopg2
-
-from nominatim.db.async_connection import DBConnection, DeadlockHandler
-
-
-@pytest.fixture
-def conn(temp_db):
- with closing(DBConnection('dbname=' + temp_db)) as connection:
- yield connection
-
-
-@pytest.fixture
-def simple_conns(temp_db):
- conn1 = psycopg2.connect('dbname=' + temp_db)
- conn2 = psycopg2.connect('dbname=' + temp_db)
-
- yield conn1.cursor(), conn2.cursor()
-
- conn1.close()
- conn2.close()
-
-
-def test_simple_query(conn, temp_db_conn):
- conn.connect()
-
- conn.perform('CREATE TABLE foo (id INT)')
- conn.wait()
-
- temp_db_conn.table_exists('foo')
-
-
-def test_wait_for_query(conn):
- conn.connect()
-
- conn.perform('SELECT pg_sleep(1)')
-
- assert not conn.is_done()
-
- conn.wait()
-
-
-def test_bad_query(conn):
- conn.connect()
-
- conn.perform('SELECT efasfjsea')
-
- with pytest.raises(psycopg2.ProgrammingError):
- conn.wait()
-
-
-def test_bad_query_ignore(temp_db):
- with closing(DBConnection('dbname=' + temp_db, ignore_sql_errors=True)) as conn:
- conn.connect()
-
- conn.perform('SELECT efasfjsea')
-
- conn.wait()
-
-
-def exec_with_deadlock(cur, sql, detector):
- with DeadlockHandler(lambda *args: detector.append(1)):
- cur.execute(sql)
-
-
-def test_deadlock(simple_conns):
- cur1, cur2 = simple_conns
-
- cur1.execute("""CREATE TABLE t1 (id INT PRIMARY KEY, t TEXT);
- INSERT into t1 VALUES (1, 'a'), (2, 'b')""")
- cur1.connection.commit()
-
- cur1.execute("UPDATE t1 SET t = 'x' WHERE id = 1")
- cur2.execute("UPDATE t1 SET t = 'x' WHERE id = 2")
-
- # This is the tricky part of the test. The first SQL command runs into
- # a lock and blocks, so we have to run it in a separate thread. When the
- # second deadlocking SQL statement is issued, Postgresql will abort one of
- # the two transactions that cause the deadlock. There is no way to tell
- # which one of the two. Therefore wrap both in a DeadlockHandler and
- # expect that exactly one of the two triggers.
- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
- deadlock_check = []
- try:
- future = executor.submit(exec_with_deadlock, cur2,
- "UPDATE t1 SET t = 'y' WHERE id = 1",
- deadlock_check)
-
- while not future.running():
- pass
-
-
- exec_with_deadlock(cur1, "UPDATE t1 SET t = 'y' WHERE id = 2",
- deadlock_check)
- finally:
- # Whatever happens, make sure the deadlock gets resolved.
- cur1.connection.rollback()
-
- future.result()
-
- assert len(deadlock_check) == 1
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for specialised connection and cursor classes.
"""
import pytest
-import psycopg2
+import psycopg
-from nominatim.db.connection import connect, get_pg_env
+import nominatim_db.db.connection as nc
@pytest.fixture
def db(dsn):
- with connect(dsn) as conn:
+ with nc.connect(dsn) as conn:
yield conn
def test_connection_table_exists(db, table_factory):
- assert not db.table_exists('foobar')
+ assert not nc.table_exists(db, 'foobar')
table_factory('foobar')
- assert db.table_exists('foobar')
+ assert nc.table_exists(db, 'foobar')
def test_has_column_no_table(db):
- assert not db.table_has_column('sometable', 'somecolumn')
+ assert not nc.table_has_column(db, 'sometable', 'somecolumn')
@pytest.mark.parametrize('name,result', [('tram', True), ('car', False)])
def test_has_column(db, table_factory, name, result):
table_factory('stuff', 'tram TEXT')
- assert db.table_has_column('stuff', name) == result
+ assert nc.table_has_column(db, 'stuff', name) == result
def test_connection_index_exists(db, table_factory, temp_db_cursor):
- assert not db.index_exists('some_index')
+ assert not nc.index_exists(db, 'some_index')
table_factory('foobar')
temp_db_cursor.execute('CREATE INDEX some_index ON foobar(id)')
- assert db.index_exists('some_index')
- assert db.index_exists('some_index', table='foobar')
- assert not db.index_exists('some_index', table='bar')
+ assert nc.index_exists(db, 'some_index')
+ assert nc.index_exists(db, 'some_index', table='foobar')
+ assert not nc.index_exists(db, 'some_index', table='bar')
def test_drop_table_existing(db, table_factory):
table_factory('dummy')
- assert db.table_exists('dummy')
+ assert nc.table_exists(db, 'dummy')
- db.drop_table('dummy')
- assert not db.table_exists('dummy')
+ nc.drop_tables(db, 'dummy')
+ assert not nc.table_exists(db, 'dummy')
-def test_drop_table_non_existsing(db):
- db.drop_table('dfkjgjriogjigjgjrdghehtre')
+def test_drop_table_non_existing(db):
+ nc.drop_tables(db, 'dfkjgjriogjigjgjrdghehtre')
+
+
+def test_drop_many_tables(db, table_factory):
+ tables = [f'table{n}' for n in range(5)]
+
+ for t in tables:
+ table_factory(t)
+ assert nc.table_exists(db, t)
+
+ nc.drop_tables(db, *tables)
+
+ for t in tables:
+ assert not nc.table_exists(db, t)
def test_drop_table_non_existing_force(db):
- with pytest.raises(psycopg2.ProgrammingError, match='.*does not exist.*'):
- db.drop_table('dfkjgjriogjigjgjrdghehtre', if_exists=False)
+ with pytest.raises(psycopg.ProgrammingError, match='.*does not exist.*'):
+ nc.drop_tables(db, 'dfkjgjriogjigjgjrdghehtre', if_exists=False)
def test_connection_server_version_tuple(db):
- ver = db.server_version_tuple()
+ ver = nc.server_version_tuple(db)
assert isinstance(ver, tuple)
assert len(ver) == 2
def test_connection_postgis_version_tuple(db, temp_db_with_extensions):
- ver = db.postgis_version_tuple()
+ ver = nc.postgis_version_tuple(db)
assert isinstance(ver, tuple)
assert len(ver) == 2
def test_cursor_scalar(db, table_factory):
table_factory('dummy')
- with db.cursor() as cur:
- assert cur.scalar('SELECT count(*) FROM dummy') == 0
+ assert nc.execute_scalar(db, 'SELECT count(*) FROM dummy') == 0
def test_cursor_scalar_many_rows(db):
- with db.cursor() as cur:
- with pytest.raises(RuntimeError):
- cur.scalar('SELECT * FROM pg_tables')
+ with pytest.raises(RuntimeError, match='Query did not return a single row.'):
+ nc.execute_scalar(db, 'SELECT * FROM pg_tables')
def test_cursor_scalar_no_rows(db, table_factory):
table_factory('dummy')
- with db.cursor() as cur:
- with pytest.raises(RuntimeError):
- cur.scalar('SELECT id FROM dummy')
+ with pytest.raises(RuntimeError, match='Query did not return a single row.'):
+ nc.execute_scalar(db, 'SELECT id FROM dummy')
def test_get_pg_env_add_variable(monkeypatch):
monkeypatch.delenv('PGPASSWORD', raising=False)
- env = get_pg_env('user=fooF')
+ env = nc.get_pg_env('user=fooF')
assert env['PGUSER'] == 'fooF'
assert 'PGPASSWORD' not in env
def test_get_pg_env_overwrite_variable(monkeypatch):
monkeypatch.setenv('PGUSER', 'some default')
- env = get_pg_env('user=overwriter')
+ env = nc.get_pg_env('user=overwriter')
assert env['PGUSER'] == 'overwriter'
def test_get_pg_env_ignore_unknown():
- env = get_pg_env('client_encoding=stuff', base_env={})
+ env = nc.get_pg_env('client_encoding=stuff', base_env={})
assert env == {}
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for property table manpulation.
"""
import pytest
-from nominatim.db import properties
+from nominatim_db.db import properties
@pytest.fixture
def property_factory(property_table, temp_db_cursor):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for SQL preprocessing.
"""
import pytest
+import pytest_asyncio
-from nominatim.db.sql_preprocessor import SQLPreprocessor
+from nominatim_db.db.sql_preprocessor import SQLPreprocessor
@pytest.fixture
def sql_factory(tmp_path):
sql_preprocessor.run_sql_file(temp_db_conn, sqlfile, bar='XX', foo='ZZ')
assert temp_db_cursor.scalar('SELECT test()') == 'ZZ XX'
+
+
+@pytest.mark.asyncio
+async def test_load_parallel_file(dsn, sql_preprocessor, tmp_path, temp_db_cursor):
+ (tmp_path / 'test.sql').write_text("""
+ CREATE TABLE foo (a TEXT);
+ CREATE TABLE foo2(a TEXT);""" +
+ "\n---\nCREATE TABLE bar (b INT);")
+
+ await sql_preprocessor.run_parallel_sql_file(dsn, 'test.sql', num_threads=4)
+
+ assert temp_db_cursor.table_exists('foo')
+ assert temp_db_cursor.table_exists('foo2')
+ assert temp_db_cursor.table_exists('bar')
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for status table manipulation.
import pytest
-import nominatim.db.status
-from nominatim.errors import UsageError
+import nominatim_db.db.status
+from nominatim_db.errors import UsageError
OSM_NODE_DATA = """\
<osm version="0.6" generator="OpenStreetMap server" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/">
"""
def iso_date(date):
- return dt.datetime.strptime(date, nominatim.db.status.ISODATE_FORMAT)\
+ return dt.datetime.strptime(date, nominatim_db.db.status.ISODATE_FORMAT)\
.replace(tzinfo=dt.timezone.utc)
table_factory('osm2pgsql_properties', 'property TEXT, value TEXT',
content=(('current_timestamp', '2024-01-03T23:45:54Z'), ))
- date = nominatim.db.status.compute_database_date(temp_db_conn, offline=offline)
+ date = nominatim_db.db.status.compute_database_date(temp_db_conn, offline=offline)
assert date == iso_date('2024-01-03T23:45:54')
table_factory('osm2pgsql_properties', 'property TEXT, value TEXT')
with pytest.raises(UsageError, match='Cannot determine database date from data in offline mode'):
- nominatim.db.status.compute_database_date(temp_db_conn, offline=True)
+ nominatim_db.db.status.compute_database_date(temp_db_conn, offline=True)
def test_compute_database_date_place_empty(place_table, temp_db_conn):
with pytest.raises(UsageError):
- nominatim.db.status.compute_database_date(temp_db_conn)
+ nominatim_db.db.status.compute_database_date(temp_db_conn)
def test_compute_database_date_valid(monkeypatch, place_row, temp_db_conn):
requested_url.append(url)
return OSM_NODE_DATA
- monkeypatch.setattr(nominatim.db.status, "get_url", mock_url)
+ monkeypatch.setattr(nominatim_db.db.status, "get_url", mock_url)
- date = nominatim.db.status.compute_database_date(temp_db_conn)
+ date = nominatim_db.db.status.compute_database_date(temp_db_conn)
assert requested_url == ['https://www.openstreetmap.org/api/0.6/node/45673/1']
assert date == iso_date('2006-01-27T22:09:10')
requested_url.append(url)
return '<osm version="0.6" generator="OpenStre'
- monkeypatch.setattr(nominatim.db.status, "get_url", mock_url)
+ monkeypatch.setattr(nominatim_db.db.status, "get_url", mock_url)
with pytest.raises(UsageError):
- nominatim.db.status.compute_database_date(temp_db_conn)
+ nominatim_db.db.status.compute_database_date(temp_db_conn)
def test_set_status_empty_table(temp_db_conn, temp_db_cursor):
date = dt.datetime.fromordinal(1000000).replace(tzinfo=dt.timezone.utc)
- nominatim.db.status.set_status(temp_db_conn, date=date)
+ nominatim_db.db.status.set_status(temp_db_conn, date=date)
assert temp_db_cursor.row_set("SELECT * FROM import_status") == \
{(date, None, True)}
def test_set_status_filled_table(temp_db_conn, temp_db_cursor):
date = dt.datetime.fromordinal(1000000).replace(tzinfo=dt.timezone.utc)
- nominatim.db.status.set_status(temp_db_conn, date=date)
+ nominatim_db.db.status.set_status(temp_db_conn, date=date)
assert temp_db_cursor.table_rows('import_status') == 1
date = dt.datetime.fromordinal(1000100).replace(tzinfo=dt.timezone.utc)
- nominatim.db.status.set_status(temp_db_conn, date=date, seq=456, indexed=False)
+ nominatim_db.db.status.set_status(temp_db_conn, date=date, seq=456, indexed=False)
assert temp_db_cursor.row_set("SELECT * FROM import_status") == \
{(date, 456, False)}
def test_set_status_missing_date(temp_db_conn, temp_db_cursor):
date = dt.datetime.fromordinal(1000000).replace(tzinfo=dt.timezone.utc)
- nominatim.db.status.set_status(temp_db_conn, date=date)
+ nominatim_db.db.status.set_status(temp_db_conn, date=date)
assert temp_db_cursor.table_rows('import_status') == 1
- nominatim.db.status.set_status(temp_db_conn, date=None, seq=456, indexed=False)
+ nominatim_db.db.status.set_status(temp_db_conn, date=None, seq=456, indexed=False)
assert temp_db_cursor.row_set("SELECT * FROM import_status") == \
{(date, 456, False)}
def test_get_status_empty_table(temp_db_conn):
- assert nominatim.db.status.get_status(temp_db_conn) == (None, None, None)
+ assert nominatim_db.db.status.get_status(temp_db_conn) == (None, None, None)
def test_get_status_success(temp_db_conn):
date = dt.datetime.fromordinal(1000000).replace(tzinfo=dt.timezone.utc)
- nominatim.db.status.set_status(temp_db_conn, date=date, seq=667, indexed=False)
+ nominatim_db.db.status.set_status(temp_db_conn, date=date, seq=667, indexed=False)
- assert nominatim.db.status.get_status(temp_db_conn) == \
+ assert nominatim_db.db.status.get_status(temp_db_conn) == \
(date, 667, False)
@pytest.mark.parametrize("new_state", [True, False])
def test_set_indexed(temp_db_conn, temp_db_cursor, old_state, new_state):
date = dt.datetime.fromordinal(1000000).replace(tzinfo=dt.timezone.utc)
- nominatim.db.status.set_status(temp_db_conn, date=date, indexed=old_state)
- nominatim.db.status.set_indexed(temp_db_conn, new_state)
+ nominatim_db.db.status.set_status(temp_db_conn, date=date, indexed=old_state)
+ nominatim_db.db.status.set_indexed(temp_db_conn, new_state)
assert temp_db_cursor.scalar("SELECT indexed FROM import_status") == new_state
def test_set_indexed_empty_status(temp_db_conn, temp_db_cursor):
- nominatim.db.status.set_indexed(temp_db_conn, True)
+ nominatim_db.db.status.set_indexed(temp_db_conn, True)
assert temp_db_cursor.table_rows("import_status") == 0
date = dt.datetime.fromordinal(1000000).replace(tzinfo=dt.timezone.utc)
start = dt.datetime.now() - dt.timedelta(hours=1)
- nominatim.db.status.set_status(temp_db_conn, date=date, seq=56)
- nominatim.db.status.log_status(temp_db_conn, start, 'index')
+ nominatim_db.db.status.set_status(temp_db_conn, date=date, seq=56)
+ nominatim_db.db.status.log_status(temp_db_conn, start, 'index')
temp_db_conn.commit()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for DB utility functions in db.utils
import pytest
-import nominatim.db.utils as db_utils
-from nominatim.errors import UsageError
+import nominatim_db.db.utils as db_utils
+from nominatim_db.errors import UsageError
def test_execute_file_success(dsn, temp_db_cursor, tmp_path):
tmpfile = tmp_path / 'test.sql'
db_utils.execute_file(dsn, tmpfile, post_code='INSERT INTO test VALUES(23)')
assert temp_db_cursor.row_set('SELECT * FROM test') == {(23, )}
-
-
-class TestCopyBuffer:
- TABLE_NAME = 'copytable'
-
- @pytest.fixture(autouse=True)
- def setup_test_table(self, table_factory):
- table_factory(self.TABLE_NAME, 'col_a INT, col_b TEXT')
-
-
- def table_rows(self, cursor):
- return cursor.row_set('SELECT * FROM ' + self.TABLE_NAME)
-
-
- def test_copybuffer_empty(self):
- with db_utils.CopyBuffer() as buf:
- buf.copy_out(None, "dummy")
-
-
- def test_all_columns(self, temp_db_cursor):
- with db_utils.CopyBuffer() as buf:
- buf.add(3, 'hum')
- buf.add(None, 'f\\t')
-
- buf.copy_out(temp_db_cursor, self.TABLE_NAME)
-
- assert self.table_rows(temp_db_cursor) == {(3, 'hum'), (None, 'f\\t')}
-
-
- def test_selected_columns(self, temp_db_cursor):
- with db_utils.CopyBuffer() as buf:
- buf.add('foo')
-
- buf.copy_out(temp_db_cursor, self.TABLE_NAME,
- columns=['col_b'])
-
- assert self.table_rows(temp_db_cursor) == {(None, 'foo')}
-
-
- def test_reordered_columns(self, temp_db_cursor):
- with db_utils.CopyBuffer() as buf:
- buf.add('one', 1)
- buf.add(' two ', 2)
-
- buf.copy_out(temp_db_cursor, self.TABLE_NAME,
- columns=['col_b', 'col_a'])
-
- assert self.table_rows(temp_db_cursor) == {(1, 'one'), (2, ' two ')}
-
-
- def test_special_characters(self, temp_db_cursor):
- with db_utils.CopyBuffer() as buf:
- buf.add('foo\tbar')
- buf.add('sun\nson')
- buf.add('\\N')
-
- buf.copy_out(temp_db_cursor, self.TABLE_NAME,
- columns=['col_b'])
-
- assert self.table_rows(temp_db_cursor) == {(None, 'foo\tbar'),
- (None, 'sun\nson'),
- (None, '\\N')}
-
-
-
-class TestCopyBufferJson:
- TABLE_NAME = 'copytable'
-
- @pytest.fixture(autouse=True)
- def setup_test_table(self, table_factory):
- table_factory(self.TABLE_NAME, 'col_a INT, col_b JSONB')
-
-
- def table_rows(self, cursor):
- cursor.execute('SELECT * FROM ' + self.TABLE_NAME)
- results = {k: v for k,v in cursor}
-
- assert len(results) == cursor.rowcount
-
- return results
-
-
- def test_json_object(self, temp_db_cursor):
- with db_utils.CopyBuffer() as buf:
- buf.add(1, json.dumps({'test': 'value', 'number': 1}))
-
- buf.copy_out(temp_db_cursor, self.TABLE_NAME)
-
- assert self.table_rows(temp_db_cursor) == \
- {1: {'test': 'value', 'number': 1}}
-
-
- def test_json_object_special_chras(self, temp_db_cursor):
- with db_utils.CopyBuffer() as buf:
- buf.add(1, json.dumps({'te\tst': 'va\nlue', 'nu"mber': None}))
-
- buf.copy_out(temp_db_cursor, self.TABLE_NAME)
-
- assert self.table_rows(temp_db_cursor) == \
- {1: {'te\tst': 'va\nlue', 'nu"mber': None}}
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tokenizer for testing.
"""
-from nominatim.data.place_info import PlaceInfo
-from nominatim.config import Configuration
+from nominatim_db.data.place_info import PlaceInfo
+from nominatim_db.config import Configuration
def create(dsn, data_dir):
""" Create a new instance of the tokenizer provided by this module.
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for running the indexing.
"""
import itertools
import pytest
+import pytest_asyncio
-from nominatim.indexer import indexer
-from nominatim.tokenizer import factory
+from nominatim_db.indexer import indexer
+from nominatim_db.tokenizer import factory
class IndexerTestDB:
self.postcode_id = itertools.count(700000)
self.conn = conn
- self.conn.set_isolation_level(0)
+ self.conn.autocimmit = True
with self.conn.cursor() as cur:
- cur.execute('CREATE EXTENSION hstore')
cur.execute("""CREATE TABLE placex (place_id BIGINT,
name HSTORE,
class TEXT,
@pytest.mark.parametrize("threads", [1, 15])
-def test_index_all_by_rank(test_db, threads, test_tokenizer):
+@pytest.mark.asyncio
+async def test_index_all_by_rank(test_db, threads, test_tokenizer):
for rank in range(31):
test_db.add_place(rank_address=rank, rank_search=rank)
test_db.add_osmline()
assert test_db.osmline_unindexed() == 1
idx = indexer.Indexer('dbname=test_nominatim_python_unittest', test_tokenizer, threads)
- idx.index_by_rank(0, 30)
+ await idx.index_by_rank(0, 30)
assert test_db.placex_unindexed() == 0
assert test_db.osmline_unindexed() == 0
@pytest.mark.parametrize("threads", [1, 15])
-def test_index_partial_without_30(test_db, threads, test_tokenizer):
+@pytest.mark.asyncio
+async def test_index_partial_without_30(test_db, threads, test_tokenizer):
for rank in range(31):
test_db.add_place(rank_address=rank, rank_search=rank)
test_db.add_osmline()
idx = indexer.Indexer('dbname=test_nominatim_python_unittest',
test_tokenizer, threads)
- idx.index_by_rank(4, 15)
+ await idx.index_by_rank(4, 15)
assert test_db.placex_unindexed() == 19
assert test_db.osmline_unindexed() == 1
@pytest.mark.parametrize("threads", [1, 15])
-def test_index_partial_with_30(test_db, threads, test_tokenizer):
+@pytest.mark.asyncio
+async def test_index_partial_with_30(test_db, threads, test_tokenizer):
for rank in range(31):
test_db.add_place(rank_address=rank, rank_search=rank)
test_db.add_osmline()
assert test_db.osmline_unindexed() == 1
idx = indexer.Indexer('dbname=test_nominatim_python_unittest', test_tokenizer, threads)
- idx.index_by_rank(28, 30)
+ await idx.index_by_rank(28, 30)
assert test_db.placex_unindexed() == 27
assert test_db.osmline_unindexed() == 0
WHERE indexed_status = 0 AND rank_address between 1 and 27""") == 0
@pytest.mark.parametrize("threads", [1, 15])
-def test_index_boundaries(test_db, threads, test_tokenizer):
+@pytest.mark.asyncio
+async def test_index_boundaries(test_db, threads, test_tokenizer):
for rank in range(4, 10):
test_db.add_admin(rank_address=rank, rank_search=rank)
for rank in range(31):
assert test_db.osmline_unindexed() == 1
idx = indexer.Indexer('dbname=test_nominatim_python_unittest', test_tokenizer, threads)
- idx.index_boundaries(0, 30)
+ await idx.index_boundaries(0, 30)
assert test_db.placex_unindexed() == 31
assert test_db.osmline_unindexed() == 1
@pytest.mark.parametrize("threads", [1, 15])
-def test_index_postcodes(test_db, threads, test_tokenizer):
+@pytest.mark.asyncio
+async def test_index_postcodes(test_db, threads, test_tokenizer):
for postcode in range(1000):
test_db.add_postcode('de', postcode)
for postcode in range(32000, 33000):
test_db.add_postcode('us', postcode)
idx = indexer.Indexer('dbname=test_nominatim_python_unittest', test_tokenizer, threads)
- idx.index_postcodes()
+ await idx.index_postcodes()
assert test_db.scalar("""SELECT count(*) FROM location_postcode
WHERE indexed_status != 0""") == 0
@pytest.mark.parametrize("analyse", [True, False])
-def test_index_full(test_db, analyse, test_tokenizer):
+@pytest.mark.asyncio
+async def test_index_full(test_db, analyse, test_tokenizer):
for rank in range(4, 10):
test_db.add_admin(rank_address=rank, rank_search=rank)
for rank in range(31):
test_db.add_postcode('de', postcode)
idx = indexer.Indexer('dbname=test_nominatim_python_unittest', test_tokenizer, 4)
- idx.index_full(analyse=analyse)
+ await idx.index_full(analyse=analyse)
assert test_db.placex_unindexed() == 0
assert test_db.osmline_unindexed() == 0
assert test_db.scalar("""SELECT count(*) FROM location_postcode
WHERE indexed_status != 0""") == 0
-
-
-@pytest.mark.parametrize("threads", [1, 15])
-def test_index_reopen_connection(test_db, threads, monkeypatch, test_tokenizer):
- monkeypatch.setattr(indexer.WorkerPool, "REOPEN_CONNECTIONS_AFTER", 15)
-
- for _ in range(1000):
- test_db.add_place(rank_address=30, rank_search=30)
-
- idx = indexer.Indexer('dbname=test_nominatim_python_unittest', test_tokenizer, threads)
- idx.index_by_rank(28, 30)
-
- assert test_db.placex_unindexed() == 0
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Legacy word table for testing with functions to prefil and test contents
of the table.
"""
+from nominatim_db.db.connection import execute_scalar
class MockIcuWordTable:
""" A word table for testing using legacy word table structure.
with self.conn.cursor() as cur:
cur.execute("""INSERT INTO word (word_token, type, word, info)
VALUES (%s, 'S', %s,
- json_build_object('class', %s,
- 'type', %s,
- 'op', %s))
+ json_build_object('class', %s::text,
+ 'type', %s::text,
+ 'op', %s::text))
""", (word_token, word, cls, typ, oper))
self.conn.commit()
word = word_tokens[0]
for token in word_tokens:
cur.execute("""INSERT INTO word (word_id, word_token, type, word, info)
- VALUES (%s, %s, 'H', %s, jsonb_build_object('lookup', %s))
+ VALUES (%s, %s, 'H', %s, jsonb_build_object('lookup', %s::text))
""", (word_id, token, word, word_tokens[0]))
self.conn.commit()
def count(self):
- with self.conn.cursor() as cur:
- return cur.scalar("SELECT count(*) FROM word")
+ return execute_scalar(self.conn, "SELECT count(*) FROM word")
def count_special(self):
- with self.conn.cursor() as cur:
- return cur.scalar("SELECT count(*) FROM word WHERE type = 'S'")
+ return execute_scalar(self.conn, "SELECT count(*) FROM word WHERE type = 'S'")
def count_housenumbers(self):
- with self.conn.cursor() as cur:
- return cur.scalar("SELECT count(*) FROM word WHERE type = 'H'")
+ return execute_scalar(self.conn, "SELECT count(*) FROM word WHERE type = 'H'")
def get_special(self):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Legacy word table for testing with functions to prefil and test contents
of the table.
"""
+from nominatim_db.db.connection import execute_scalar
class MockLegacyWordTable:
""" A word table for testing using legacy word table structure.
def count(self):
- with self.conn.cursor() as cur:
- return cur.scalar("SELECT count(*) FROM word")
+ return execute_scalar(self.conn, "SELECT count(*) FROM word")
def count_special(self):
- with self.conn.cursor() as cur:
- return cur.scalar("SELECT count(*) FROM word WHERE class != 'place'")
+ return execute_scalar(self.conn, "SELECT count(*) FROM word WHERE class != 'place'")
def get_special(self):
with self.conn.cursor() as cur:
- cur.execute("""SELECT word_token, word, class, type, operator
+ cur.execute("""SELECT word_token, word, class as cls, type, operator
FROM word WHERE class != 'place'""")
result = set((tuple(row) for row in cur))
assert len(result) == cur.rowcount, "Word table has duplicates."
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Custom mocks for testing.
"""
import itertools
-import psycopg2.extras
-
-from nominatim.db import properties
+from nominatim_db.db import properties
# This must always point to the mock word table for the default tokenizer.
from mock_icu_word_table import MockIcuWordTable as MockWordTable
admin_level=None, address=None, extratags=None, geom='POINT(10 4)',
country=None, housenumber=None, rank_search=30):
with self.conn.cursor() as cur:
- psycopg2.extras.register_hstore(cur)
cur.execute("""INSERT INTO placex (place_id, osm_type, osm_id, class,
type, name, admin_level, address,
housenumber, rank_search,
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the sanitizer that normalizes housenumbers.
"""
import pytest
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.place_info import PlaceInfo
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+from nominatim_db.data.place_info import PlaceInfo
@pytest.fixture
def sanitize(request, def_config):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the sanitizer that normalizes postcodes.
"""
import pytest
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.place_info import PlaceInfo
-from nominatim.data import country_info
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+from nominatim_db.data.place_info import PlaceInfo
+from nominatim_db.data import country_info
@pytest.fixture
def sanitize(def_config, request):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for sanitizer that clean up TIGER tags.
"""
import pytest
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.place_info import PlaceInfo
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+from nominatim_db.data.place_info import PlaceInfo
class TestCleanTigerTags:
-# SPDX-License-Identifier: GPL-2.0-only\r
+# SPDX-License-Identifier: GPL-3.0-or-later\r
#\r
# This file is part of Nominatim. (https://nominatim.org)\r
#\r
-# Copyright (C) 2023 by the Nominatim developer community.\r
+# Copyright (C) 2024 by the Nominatim developer community.\r
# For a full list of authors see the git log.\r
"""\r
Tests for the sanitizer that normalizes housenumbers.\r
"""\r
import pytest\r
\r
-\r
-from nominatim.data.place_info import PlaceInfo\r
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer\r
+from nominatim_db.data.place_info import PlaceInfo\r
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer\r
\r
\r
class TestWithDefault:\r
name='foo', ref='foo', name_pqr='bar', ref_pqr='baz')\r
\r
assert res == [('bar', 'name', 'pqr'), ('baz', 'ref', 'pqr'),\r
- ('foo', 'name', ''), ('foo', 'ref', '')]
\ No newline at end of file
+ ('foo', 'name', ''), ('foo', 'ref', '')]\r
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for sanitizer configuration helper functions.
"""
import pytest
-from nominatim.errors import UsageError
-from nominatim.tokenizer.sanitizers.config import SanitizerConfig
+from nominatim_db.errors import UsageError
+from nominatim_db.tokenizer.sanitizers.config import SanitizerConfig
def test_string_list_default_empty():
assert SanitizerConfig().get_string_list('op') == []
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the sanitizer that splits multivalue lists.
"""
import pytest
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.place_info import PlaceInfo
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+from nominatim_db.data.place_info import PlaceInfo
-from nominatim.errors import UsageError
+from nominatim_db.errors import UsageError
class TestSplitName:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the sanitizer that handles braced suffixes.
"""
import pytest
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.place_info import PlaceInfo
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+from nominatim_db.data.place_info import PlaceInfo
class TestStripBrace:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the sanitizer that enables language-dependent analyzers.
"""
import pytest
-from nominatim.data.place_info import PlaceInfo
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
-from nominatim.data.country_info import setup_country_config
+from nominatim_db.data.place_info import PlaceInfo
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+from nominatim_db.data.country_info import setup_country_config
class TestWithDefaults:
-from nominatim.data.place_info import PlaceInfo
-from nominatim.data.place_name import PlaceName
-from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This file is part of Nominatim. (https://nominatim.org)
+#
+# Copyright (C) 2024 by the Nominatim developer community.
+# For a full list of authors see the git log.
from typing import Mapping, Optional, List
import pytest
+from nominatim_db.data.place_info import PlaceInfo
+from nominatim_db.data.place_name import PlaceName
+from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
+
class TestTagJapanese:
@pytest.fixture(autouse=True)
def setup_country(self, def_config):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for creating new tokenizers.
"""
import pytest
-from nominatim.db import properties
-from nominatim.tokenizer import factory
-from nominatim.errors import UsageError
+from nominatim_db.db import properties
+from nominatim_db.tokenizer import factory
+from nominatim_db.errors import UsageError
from dummy_tokenizer import DummyTokenizer
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for ICU tokenizer.
import pytest
-from nominatim.tokenizer import icu_tokenizer
-import nominatim.tokenizer.icu_rule_loader
-from nominatim.db import properties
-from nominatim.db.sql_preprocessor import SQLPreprocessor
-from nominatim.data.place_info import PlaceInfo
+from nominatim_db.tokenizer import icu_tokenizer
+import nominatim_db.tokenizer.icu_rule_loader
+from nominatim_db.db import properties
+from nominatim_db.db.sql_preprocessor import SQLPreprocessor
+from nominatim_db.data.place_info import PlaceInfo
from mock_icu_word_table import MockIcuWordTable
cfgstr['token-analysis'].append({'id': '@postcode',
'analyzer': 'postcodes'})
(test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
- tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
+ tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
return tok.name_analyzer()
tok = tokenizer_factory()
tok.init_new_db(test_config)
- assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
+ assert db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
.startswith(':: lower ();')
assert test_content == set((('1133', ), ))
-def test_finalize_import(tokenizer_factory, temp_db_conn,
- temp_db_cursor, test_config, sql_preprocessor_cfg):
+def test_finalize_import(tokenizer_factory, temp_db_cursor,
+ test_config, sql_preprocessor_cfg):
tok = tokenizer_factory()
tok.init_new_db(test_config)
- assert not temp_db_conn.index_exists('idx_word_word_id')
+ assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
tok.finalize_import(test_config)
- assert temp_db_conn.index_exists('idx_word_word_id')
+ assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
def test_check_database(test_config, tokenizer_factory,
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for converting a config file to ICU rules.
import pytest
import yaml
-from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
-from nominatim.errors import UsageError
+from nominatim_db.tokenizer.icu_rule_loader import ICURuleLoader
+from nominatim_db.errors import UsageError
from icu import Transliterator
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for legacy tokenizer.
import pytest
-from nominatim.data.place_info import PlaceInfo
-from nominatim.tokenizer import legacy_tokenizer
-from nominatim.db import properties
-from nominatim.errors import UsageError
+from nominatim_db.data.place_info import PlaceInfo
+from nominatim_db.tokenizer import legacy_tokenizer
+from nominatim_db.db import properties
+from nominatim_db.errors import UsageError
from mock_legacy_word_table import MockLegacyWordTable
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for execution of the sanitztion step.
"""
import pytest
-from nominatim.errors import UsageError
-import nominatim.tokenizer.place_sanitizer as sanitizer
-from nominatim.data.place_info import PlaceInfo
+from nominatim_db.errors import UsageError
+import nominatim_db.tokenizer.place_sanitizer as sanitizer
+from nominatim_db.data.place_info import PlaceInfo
def test_placeinfo_clone_new_name():
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for special postcode analysis and variant generation.
from icu import Transliterator
-import nominatim.tokenizer.token_analysis.postcodes as module
-from nominatim.data.place_name import PlaceName
-from nominatim.errors import UsageError
+import nominatim_db.tokenizer.token_analysis.postcodes as module
+from nominatim_db.data.place_name import PlaceName
+from nominatim_db.errors import UsageError
DEFAULT_NORMALIZATION = """ :: NFD ();
'🜳' > ' ';
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for import name normalisation and variant generation.
from icu import Transliterator
-import nominatim.tokenizer.token_analysis.generic as module
-from nominatim.errors import UsageError
+import nominatim_db.tokenizer.token_analysis.generic as module
+from nominatim_db.errors import UsageError
DEFAULT_NORMALIZATION = """ :: NFD ();
'🜳' > ' ';
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for generic token analysis, mutation part.
from icu import Transliterator
-import nominatim.tokenizer.token_analysis.generic as module
-from nominatim.errors import UsageError
+import nominatim_db.tokenizer.token_analysis.generic as module
+from nominatim_db.errors import UsageError
DEFAULT_NORMALIZATION = """ '🜳' > ' ';
[[:Nonspacing Mark:] [:Cf:]] >;
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
import pytest
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for functions to add additional data to the database.
import pytest
-from nominatim.tools import add_osm_data
+from nominatim_db.tools import add_osm_data
class CaptureGetUrl:
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for maintenance and analysis functions.
"""
import pytest
-from nominatim.errors import UsageError
-from nominatim.tools import admin
-from nominatim.tokenizer import factory
-from nominatim.db.sql_preprocessor import SQLPreprocessor
+from nominatim_db.errors import UsageError
+from nominatim_db.tools import admin
+from nominatim_db.tokenizer import factory
+from nominatim_db.db.sql_preprocessor import SQLPreprocessor
@pytest.fixture(autouse=True)
def create_placex_table(project_env, tokenizer_mock, temp_db_cursor, placex_table):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for database integrity checks.
"""
import pytest
-from nominatim.tools import check_database as chkdb
-import nominatim.version
+from nominatim_db.tools import check_database as chkdb
+import nominatim_db.version
def test_check_database_unknown_db(def_config, monkeypatch):
monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'pgsql:dbname=fjgkhughwgh2423gsags')
def test_check_database_version_good(property_table, temp_db_conn, def_config):
property_table.set('database_version',
- '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(nominatim.version.NOMINATIM_VERSION))
+ str(nominatim_db.version.NOMINATIM_VERSION))
assert chkdb.check_database_version(temp_db_conn, def_config) == chkdb.CheckState.OK
def test_check_database_version_bad(property_table, temp_db_conn, def_config):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for functions to import a new database.
"""
from pathlib import Path
-from contextlib import closing
import pytest
-import psycopg2
+import pytest_asyncio
+import psycopg
+from psycopg import sql as pysql
-from nominatim.tools import database_import
-from nominatim.errors import UsageError
+from nominatim_db.tools import database_import
+from nominatim_db.errors import UsageError
class TestDatabaseSetup:
DBNAME = 'test_nominatim_python_unittest'
@pytest.fixture(autouse=True)
def setup_nonexistant_db(self):
- conn = psycopg2.connect(database='postgres')
-
- try:
- conn.set_isolation_level(0)
+ with psycopg.connect(dbname='postgres', autocommit=True) as conn:
with conn.cursor() as cur:
cur.execute(f'DROP DATABASE IF EXISTS {self.DBNAME}')
with conn.cursor() as cur:
cur.execute(f'DROP DATABASE IF EXISTS {self.DBNAME}')
- finally:
- conn.close()
+
@pytest.fixture
def cursor(self):
- conn = psycopg2.connect(database=self.DBNAME)
-
- try:
+ with psycopg.connect(dbname=self.DBNAME) as conn:
with conn.cursor() as cur:
yield cur
- finally:
- conn.close()
def conn(self):
- return closing(psycopg2.connect(database=self.DBNAME))
+ return psycopg.connect(dbname=self.DBNAME)
def test_setup_skeleton(self):
ignore_errors=True)
-def test_import_osm_data_drop(table_factory, temp_db_conn, tmp_path, osm2pgsql_options):
+def test_import_osm_data_drop(table_factory, temp_db_cursor, tmp_path, osm2pgsql_options):
table_factory('place', content=((1, ), ))
table_factory('planet_osm_nodes')
database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options, drop=True)
assert not flatfile.exists()
- assert not temp_db_conn.table_exists('planet_osm_nodes')
+ assert not temp_db_cursor.table_exists('planet_osm_nodes')
def test_import_osm_data_default_cache(table_factory, osm2pgsql_options, capfd):
@pytest.mark.parametrize("threads", (1, 5))
-def test_load_data(dsn, place_row, placex_table, osmline_table,
+@pytest.mark.asyncio
+async def test_load_data(dsn, place_row, placex_table, osmline_table,
temp_db_cursor, threads):
for func in ('precompute_words', 'getorcreate_housenumber_id', 'make_standard_name'):
- temp_db_cursor.execute(f"""CREATE FUNCTION {func} (src TEXT)
- RETURNS TEXT AS $$ SELECT 'a'::TEXT $$ LANGUAGE SQL
- """)
+ temp_db_cursor.execute(pysql.SQL("""CREATE FUNCTION {} (src TEXT)
+ RETURNS TEXT AS $$ SELECT 'a'::TEXT $$ LANGUAGE SQL
+ """).format(pysql.Identifier(func)))
for oid in range(100, 130):
place_row(osm_id=oid)
place_row(osm_type='W', osm_id=342, cls='place', typ='houses',
geom='SRID=4326;LINESTRING(0 0, 10 10)')
- database_import.load_data(dsn, threads)
+ await database_import.load_data(dsn, threads)
assert temp_db_cursor.table_rows('placex') == 30
assert temp_db_cursor.table_rows('location_property_osmline') == 1
@pytest.mark.parametrize("drop", [True, False])
- def test_create_search_indices(self, temp_db_conn, temp_db_cursor, drop):
+ @pytest.mark.asyncio
+ async def test_create_search_indices(self, temp_db_conn, temp_db_cursor, drop):
self.write_sql('indices.sql',
"""CREATE FUNCTION test() RETURNS bool
AS $$ SELECT {{drop}} $$ LANGUAGE SQL""")
- database_import.create_search_indices(temp_db_conn, self.config, drop)
+ await database_import.create_search_indices(temp_db_conn, self.config, drop)
temp_db_cursor.scalar('SELECT test()') == drop
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for tools.exec_utils module.
import pytest
-from nominatim.config import Configuration
-import nominatim.tools.exec_utils as exec_utils
-import nominatim.paths
-
-
-### run_osm2pgsql
+from nominatim_db.config import Configuration
+import nominatim_db.tools.exec_utils as exec_utils
def test_run_osm2pgsql(osm2pgsql_options):
osm2pgsql_options['append'] = False
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for freeze functions (removing unused database parts).
"""
-from nominatim.tools import freeze
+from nominatim_db.tools import freeze
NOMINATIM_RUNTIME_TABLES = [
'country_name', 'country_osm_grid',
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for import special phrases methods
"""
from shutil import copyfile
import pytest
-from nominatim.tools.special_phrases.sp_importer import SPImporter
-from nominatim.tools.special_phrases.sp_wiki_loader import SPWikiLoader
-from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
-from nominatim.errors import UsageError
+from nominatim_db.tools.special_phrases.sp_importer import SPImporter
+from nominatim_db.tools.special_phrases.sp_wiki_loader import SPWikiLoader
+from nominatim_db.tools.special_phrases.special_phrase import SpecialPhrase
+from nominatim_db.errors import UsageError
from cursor import CursorForTesting
assert isinstance(black_list, dict) and isinstance(white_list, dict)
-def test_create_place_classtype_indexes(temp_db_with_extensions, temp_db_conn,
+def test_create_place_classtype_indexes(temp_db_with_extensions,
+ temp_db_conn, temp_db_cursor,
table_factory, sp_importer):
"""
Test that _create_place_classtype_indexes() create the
table_factory(table_name, 'place_id BIGINT, centroid GEOMETRY')
sp_importer._create_place_classtype_indexes('', phrase_class, phrase_type)
+ temp_db_conn.commit()
- assert check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type)
+ assert check_placeid_and_centroid_indexes(temp_db_cursor, phrase_class, phrase_type)
-def test_create_place_classtype_table(temp_db_conn, placex_table, sp_importer):
+def test_create_place_classtype_table(temp_db_conn, temp_db_cursor, placex_table, sp_importer):
"""
Test that _create_place_classtype_table() create
the right place_classtype table.
phrase_class = 'class'
phrase_type = 'type'
sp_importer._create_place_classtype_table('', phrase_class, phrase_type)
+ temp_db_conn.commit()
- assert check_table_exist(temp_db_conn, phrase_class, phrase_type)
+ assert check_table_exist(temp_db_cursor, phrase_class, phrase_type)
-def test_grant_access_to_web_user(temp_db_conn, table_factory, def_config, sp_importer):
+def test_grant_access_to_web_user(temp_db_conn, temp_db_cursor, table_factory,
+ def_config, sp_importer):
"""
Test that _grant_access_to_webuser() give
right access to the web user.
table_factory(table_name)
sp_importer._grant_access_to_webuser(phrase_class, phrase_type)
+ temp_db_conn.commit()
- assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
+ assert check_grant_access(temp_db_cursor, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
def test_create_place_classtype_table_and_indexes(
- temp_db_conn, def_config, placex_table,
- sp_importer):
+ temp_db_cursor, def_config, placex_table,
+ sp_importer, temp_db_conn):
"""
Test that _create_place_classtype_table_and_indexes()
create the right place_classtype tables and place_id indexes
pairs = set([('class1', 'type1'), ('class2', 'type2')])
sp_importer._create_classtype_table_and_indexes(pairs)
+ temp_db_conn.commit()
for pair in pairs:
- assert check_table_exist(temp_db_conn, pair[0], pair[1])
- assert check_placeid_and_centroid_indexes(temp_db_conn, pair[0], pair[1])
- assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, pair[0], pair[1])
+ assert check_table_exist(temp_db_cursor, pair[0], pair[1])
+ assert check_placeid_and_centroid_indexes(temp_db_cursor, pair[0], pair[1])
+ assert check_grant_access(temp_db_cursor, def_config.DATABASE_WEBUSER, pair[0], pair[1])
def test_remove_non_existent_tables_from_db(sp_importer, default_phrases,
- temp_db_conn):
+ temp_db_conn, temp_db_cursor):
"""
Check for the remove_non_existent_phrases_from_db() method.
"""
sp_importer._remove_non_existent_tables_from_db()
+ temp_db_conn.commit()
- # Changes are not committed yet. Use temp_db_conn for checking results.
- with temp_db_conn.cursor(cursor_factory=CursorForTesting) as cur:
- assert cur.row_set(query_tables) \
+ assert temp_db_cursor.row_set(query_tables) \
== {('place_classtype_testclasstypetable_to_keep', )}
@pytest.mark.parametrize("should_replace", [(True), (False)])
-def test_import_phrases(monkeypatch, temp_db_conn, def_config, sp_importer,
+def test_import_phrases(monkeypatch, temp_db_cursor, def_config, sp_importer,
placex_table, table_factory, tokenizer_mock,
xml_wiki_content, should_replace):
"""
table_factory('place_classtype_amenity_animal_shelter')
table_factory('place_classtype_wrongclass_wrongtype')
- monkeypatch.setattr('nominatim.tools.special_phrases.sp_wiki_loader._get_wiki_content',
+ monkeypatch.setattr('nominatim_db.tools.special_phrases.sp_wiki_loader._get_wiki_content',
lambda lang: xml_wiki_content)
tokenizer = tokenizer_mock()
class_test = 'aerialway'
type_test = 'zip_line'
- assert check_table_exist(temp_db_conn, class_test, type_test)
- assert check_placeid_and_centroid_indexes(temp_db_conn, class_test, type_test)
- assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, class_test, type_test)
- assert check_table_exist(temp_db_conn, 'amenity', 'animal_shelter')
+ assert check_table_exist(temp_db_cursor, class_test, type_test)
+ assert check_placeid_and_centroid_indexes(temp_db_cursor, class_test, type_test)
+ assert check_grant_access(temp_db_cursor, def_config.DATABASE_WEBUSER, class_test, type_test)
+ assert check_table_exist(temp_db_cursor, 'amenity', 'animal_shelter')
if should_replace:
- assert not check_table_exist(temp_db_conn, 'wrong_class', 'wrong_type')
+ assert not check_table_exist(temp_db_cursor, 'wrong_class', 'wrong_type')
- assert temp_db_conn.table_exists('place_classtype_amenity_animal_shelter')
+ assert temp_db_cursor.table_exists('place_classtype_amenity_animal_shelter')
if should_replace:
- assert not temp_db_conn.table_exists('place_classtype_wrongclass_wrongtype')
+ assert not temp_db_cursor.table_exists('place_classtype_wrongclass_wrongtype')
-def check_table_exist(temp_db_conn, phrase_class, phrase_type):
+def check_table_exist(temp_db_cursor, phrase_class, phrase_type):
"""
Verify that the place_classtype table exists for the given
phrase_class and phrase_type.
"""
- return temp_db_conn.table_exists('place_classtype_{}_{}'.format(phrase_class, phrase_type))
+ return temp_db_cursor.table_exists('place_classtype_{}_{}'.format(phrase_class, phrase_type))
-def check_grant_access(temp_db_conn, user, phrase_class, phrase_type):
+def check_grant_access(temp_db_cursor, user, phrase_class, phrase_type):
"""
Check that the web user has been granted right access to the
place_classtype table of the given phrase_class and phrase_type.
"""
table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
- with temp_db_conn.cursor() as temp_db_cursor:
- temp_db_cursor.execute("""
- SELECT * FROM information_schema.role_table_grants
- WHERE table_name='{}'
- AND grantee='{}'
- AND privilege_type='SELECT'""".format(table_name, user))
- return temp_db_cursor.fetchone()
+ temp_db_cursor.execute("""
+ SELECT * FROM information_schema.role_table_grants
+ WHERE table_name='{}'
+ AND grantee='{}'
+ AND privilege_type='SELECT'""".format(table_name, user))
+ return temp_db_cursor.fetchone()
-def check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type):
+def check_placeid_and_centroid_indexes(temp_db_cursor, phrase_class, phrase_type):
"""
Check that the place_id index and centroid index exist for the
place_classtype table of the given phrase_class and phrase_type.
"""
+ table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
index_prefix = 'idx_place_classtype_{}_{}_'.format(phrase_class, phrase_type)
return (
- temp_db_conn.index_exists(index_prefix + 'centroid')
+ temp_db_cursor.index_exists(table_name, index_prefix + 'centroid')
and
- temp_db_conn.index_exists(index_prefix + 'place_id')
+ temp_db_cursor.index_exists(table_name, index_prefix + 'place_id')
)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for migration functions
"""
import pytest
-import psycopg2.extras
-from nominatim.tools import migration
-from nominatim.errors import UsageError
-import nominatim.version
+from nominatim_db.tools import migration
+from nominatim_db.errors import UsageError
+from nominatim_db.db.connection import server_version_tuple
+import nominatim_db.version
from mock_legacy_word_table import MockLegacyWordTable
def test_set_up_migration_for_36(temp_db_with_extensions, temp_db_cursor,
table_factory, def_config, monkeypatch,
postprocess_mock):
- psycopg2.extras.register_hstore(temp_db_cursor)
# don't actually run any migration, except the property table creation
monkeypatch.setattr(migration, '_MIGRATION_FUNCTIONS',
[((3, 5, 0, 99), migration.add_nominatim_property_table)])
WHERE property = 'database_version'""")
-def test_already_at_version(def_config, property_table):
+def test_already_at_version(temp_db_with_extensions, def_config, property_table):
property_table.set('database_version',
- '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(nominatim.version.NOMINATIM_VERSION))
+ str(nominatim_db.version.NOMINATIM_VERSION))
assert migration.migrate(def_config, {}) == 0
-def test_run_single_migration(def_config, temp_db_cursor, property_table,
- monkeypatch, postprocess_mock):
- oldversion = [x for x in nominatim.version.NOMINATIM_VERSION]
+def test_run_single_migration(temp_db_with_extensions, def_config, temp_db_cursor,
+ property_table, monkeypatch, postprocess_mock):
+ oldversion = [x for x in nominatim_db.version.NOMINATIM_VERSION]
oldversion[0] -= 1
property_table.set('database_version',
- '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(oldversion))
+ str(nominatim_db.version.NominatimVersion(*oldversion)))
done = {'old': False, 'new': False}
def _migration(**_):
oldversion[0] = 0
monkeypatch.setattr(migration, '_MIGRATION_FUNCTIONS',
[(tuple(oldversion), _old_migration),
- (nominatim.version.NOMINATIM_VERSION, _migration)])
+ (nominatim_db.version.NOMINATIM_VERSION, _migration)])
assert migration.migrate(def_config, {}) == 0
assert done['new']
assert not done['old']
- assert property_table.get('database_version') == \
- '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(nominatim.version.NOMINATIM_VERSION)
+ assert property_table.get('database_version') == str(nominatim_db.version.NOMINATIM_VERSION)
###### Tests for specific migrations
migration.create_tiger_housenumber_index(temp_db_conn)
temp_db_conn.commit()
- if temp_db_conn.server_version_tuple() >= (11, 0, 0):
+ if server_version_tuple(temp_db_conn) >= (11, 0, 0):
assert temp_db_cursor.index_exists('location_property_tiger',
'idx_location_property_tiger_housenumber_migrated')
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for functions to maintain the artificial postcode table.
import pytest
-from nominatim.tools import postcodes
-from nominatim.data import country_info
+from nominatim_db.tools import postcodes
+from nominatim_db.data import country_info
import dummy_tokenizer
class MockPostcodeTable:
country_code, postcode,
geometry)
VALUES (nextval('seq_place'), 1, %s, %s,
- 'SRID=4326;POINT(%s %s)')""",
+ ST_SetSRID(ST_MakePoint(%s, %s), 4326))""",
(country, postcode, x, y))
self.conn.commit()
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for various refresh functions.
import pytest
-from nominatim.tools import refresh
+from nominatim_db.tools import refresh
+from nominatim_db.db.connection import postgis_version_tuple
def test_refresh_import_wikipedia_not_existing(dsn):
assert refresh.import_wikipedia_articles(dsn, Path('.')) == 1
def test_refresh_import_secondary_importance_testdb(dsn, src_dir, temp_db_conn, temp_db_cursor):
temp_db_cursor.execute('CREATE EXTENSION postgis')
- if temp_db_conn.postgis_version_tuple()[0] < 3:
+ if postgis_version_tuple(temp_db_conn)[0] < 3:
assert refresh.import_secondary_importance(dsn, src_dir / 'test' / 'testdb') > 0
else:
temp_db_cursor.execute('CREATE EXTENSION postgis_raster')
assert refresh.import_secondary_importance(dsn, src_dir / 'test' / 'testdb') == 0
- assert temp_db_conn.table_exists('secondary_importance')
+ assert temp_db_cursor.table_exists('secondary_importance')
@pytest.mark.parametrize("replace", (True, False))
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for function for importing address ranks.
import pytest
-from nominatim.tools.refresh import load_address_levels, load_address_levels_from_config
+from nominatim_db.tools.refresh import load_address_levels, load_address_levels_from_config
def test_load_ranks_def_config(temp_db_conn, temp_db_cursor, def_config):
load_address_levels_from_config(temp_db_conn, def_config)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for creating PL/pgSQL functions for Nominatim.
"""
import pytest
-from nominatim.tools.refresh import create_functions
+from nominatim_db.tools.refresh import create_functions
class TestCreateFunctions:
@pytest.fixture(autouse=True)
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for setting up the website scripts.
import pytest
-from nominatim.tools import refresh
+from nominatim_db.tools import refresh
@pytest.fixture
def test_script(tmp_path):
import pytest
-from nominatim.tools.refresh import import_wikipedia_articles, recompute_importance, create_functions
+from nominatim_db.tools.refresh import import_wikipedia_articles, recompute_importance, create_functions
@pytest.fixture
def wiki_csv(tmp_path, sql_preprocessor):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for replication functionality.
import pytest
from osmium.replication.server import OsmosisState
-import nominatim.tools.replication
-import nominatim.db.status as status
-from nominatim.errors import UsageError
+import nominatim_db.tools.replication
+import nominatim_db.db.status as status
+from nominatim_db.errors import UsageError
OSM_NODE_DATA = """\
<osm version="0.6" generator="OpenStreetMap server" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/">
def test_init_replication_bad_base_url(monkeypatch, place_row, temp_db_conn):
place_row(osm_type='N', osm_id=100)
- monkeypatch.setattr(nominatim.db.status, "get_url", lambda u: OSM_NODE_DATA)
+ monkeypatch.setattr(status, "get_url", lambda u: OSM_NODE_DATA)
with pytest.raises(UsageError, match="Failed to reach replication service"):
- nominatim.tools.replication.init_replication(temp_db_conn, 'https://test.io')
+ nominatim_db.tools.replication.init_replication(temp_db_conn, 'https://test.io')
def test_init_replication_success(monkeypatch, place_row, temp_db_conn, temp_db_cursor):
place_row(osm_type='N', osm_id=100)
- monkeypatch.setattr(nominatim.db.status, "get_url", lambda u: OSM_NODE_DATA)
- monkeypatch.setattr(nominatim.tools.replication.ReplicationServer,
+ monkeypatch.setattr(status, "get_url", lambda u: OSM_NODE_DATA)
+ monkeypatch.setattr(nominatim_db.tools.replication.ReplicationServer,
"timestamp_to_sequence",
lambda self, date: 234)
- nominatim.tools.replication.init_replication(temp_db_conn, 'https://test.io')
+ nominatim_db.tools.replication.init_replication(temp_db_conn, 'https://test.io')
expected_date = dt.datetime.strptime('2006-01-27T19:09:10', status.ISODATE_FORMAT)\
.replace(tzinfo=dt.timezone.utc)
### checking for updates
def test_check_for_updates_empty_status_table(temp_db_conn):
- assert nominatim.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == 254
+ assert nominatim_db.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == 254
def test_check_for_updates_seq_not_set(temp_db_conn):
status.set_status(temp_db_conn, dt.datetime.now(dt.timezone.utc))
- assert nominatim.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == 254
+ assert nominatim_db.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == 254
def test_check_for_updates_no_state(monkeypatch, temp_db_conn):
status.set_status(temp_db_conn, dt.datetime.now(dt.timezone.utc), seq=345)
- monkeypatch.setattr(nominatim.tools.replication.ReplicationServer,
+ monkeypatch.setattr(nominatim_db.tools.replication.ReplicationServer,
"get_state_info", lambda self: None)
- assert nominatim.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == 253
+ assert nominatim_db.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == 253
@pytest.mark.parametrize("server_sequence,result", [(344, 2), (345, 2), (346, 0)])
date = dt.datetime.now(dt.timezone.utc)
status.set_status(temp_db_conn, date, seq=345)
- monkeypatch.setattr(nominatim.tools.replication.ReplicationServer,
+ monkeypatch.setattr(nominatim_db.tools.replication.ReplicationServer,
"get_state_info",
lambda self: OsmosisState(server_sequence, date))
- assert nominatim.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == result
+ assert nominatim_db.tools.replication.check_for_updates(temp_db_conn, 'https://test.io') == result
### updating
def test_update_empty_status_table(dsn):
with pytest.raises(UsageError):
- nominatim.tools.replication.update(dsn, {})
+ nominatim_db.tools.replication.update(dsn, {})
def test_update_already_indexed(temp_db_conn, dsn):
status.set_status(temp_db_conn, dt.datetime.now(dt.timezone.utc), seq=34, indexed=False)
- assert nominatim.tools.replication.update(dsn, dict(indexed_only=True)) \
- == nominatim.tools.replication.UpdateState.MORE_PENDING
+ assert nominatim_db.tools.replication.update(dsn, dict(indexed_only=True)) \
+ == nominatim_db.tools.replication.UpdateState.MORE_PENDING
def test_update_no_data_no_sleep(monkeypatch, temp_db_conn, dsn, update_options):
date = dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=1)
status.set_status(temp_db_conn, date, seq=34)
- monkeypatch.setattr(nominatim.tools.replication.ReplicationServer,
+ monkeypatch.setattr(nominatim_db.tools.replication.ReplicationServer,
"apply_diffs",
lambda *args, **kwargs: None)
sleeptime = []
monkeypatch.setattr(time, 'sleep', sleeptime.append)
- assert nominatim.tools.replication.update(dsn, update_options) \
- == nominatim.tools.replication.UpdateState.NO_CHANGES
+ assert nominatim_db.tools.replication.update(dsn, update_options) \
+ == nominatim_db.tools.replication.UpdateState.NO_CHANGES
assert not sleeptime
date = dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=30)
status.set_status(temp_db_conn, date, seq=34)
- monkeypatch.setattr(nominatim.tools.replication.ReplicationServer,
+ monkeypatch.setattr(nominatim_db.tools.replication.ReplicationServer,
"apply_diffs",
lambda *args, **kwargs: None)
sleeptime = []
monkeypatch.setattr(time, 'sleep', sleeptime.append)
- assert nominatim.tools.replication.update(dsn, update_options) \
- == nominatim.tools.replication.UpdateState.NO_CHANGES
+ assert nominatim_db.tools.replication.update(dsn, update_options) \
+ == nominatim_db.tools.replication.UpdateState.NO_CHANGES
assert len(sleeptime) == 1
assert sleeptime[0] < 3600
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for methods of the SPCsvLoader class.
"""
import pytest
-from nominatim.errors import UsageError
-from nominatim.tools.special_phrases.sp_csv_loader import SPCsvLoader
-from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
+from nominatim_db.errors import UsageError
+from nominatim_db.tools.special_phrases.sp_csv_loader import SPCsvLoader
+from nominatim_db.tools.special_phrases.special_phrase import SpecialPhrase
@pytest.fixture
def sp_csv_loader(src_dir):
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for methods of the SPWikiLoader class.
"""
import pytest
-from nominatim.tools.special_phrases.sp_wiki_loader import SPWikiLoader
+from nominatim_db.tools.special_phrases.sp_wiki_loader import SPWikiLoader
@pytest.fixture
xml_test_content = src_dir / 'test' / 'testdata' / 'special_phrases_test_content.txt'
return xml_test_content.read_text()
- monkeypatch.setattr('nominatim.tools.special_phrases.sp_wiki_loader._get_wiki_content',
+ monkeypatch.setattr('nominatim_db.tools.special_phrases.sp_wiki_loader._get_wiki_content',
_mock_wiki_content)
return loader
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Test for tiger data function
from textwrap import dedent
import pytest
+import pytest_asyncio
-from nominatim.tools import tiger_data, freeze
-from nominatim.errors import UsageError
+from nominatim_db.db.connection import execute_scalar
+from nominatim_db.tools import tiger_data, freeze
+from nominatim_db.errors import UsageError
class MockTigerTable:
cur.execute("CREATE TABLE place (number INTEGER)")
def count(self):
- with self.conn.cursor() as cur:
- return cur.scalar("SELECT count(*) FROM tiger")
+ return execute_scalar(self.conn, "SELECT count(*) FROM tiger")
def row(self):
with self.conn.cursor() as cur:
@pytest.mark.parametrize("threads", (1, 5))
-def test_add_tiger_data(def_config, src_dir, tiger_table, tokenizer_mock, threads):
- tiger_data.add_tiger_data(str(src_dir / 'test' / 'testdb' / 'tiger'),
- def_config, threads, tokenizer_mock())
+@pytest.mark.asyncio
+async def test_add_tiger_data(def_config, src_dir, tiger_table, tokenizer_mock, threads):
+ await tiger_data.add_tiger_data(str(src_dir / 'test' / 'testdb' / 'tiger'),
+ def_config, threads, tokenizer_mock())
assert tiger_table.count() == 6213
-def test_add_tiger_data_database_frozen(def_config, temp_db_conn, tiger_table, tokenizer_mock,
+@pytest.mark.asyncio
+async def test_add_tiger_data_database_frozen(def_config, temp_db_conn, tiger_table, tokenizer_mock,
tmp_path):
freeze.drop_update_tables(temp_db_conn)
with pytest.raises(UsageError) as excinfo:
- tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
assert "database frozen" in str(excinfo.value)
assert tiger_table.count() == 0
-def test_add_tiger_data_no_files(def_config, tiger_table, tokenizer_mock,
+
+@pytest.mark.asyncio
+async def test_add_tiger_data_no_files(def_config, tiger_table, tokenizer_mock,
tmp_path):
- tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
assert tiger_table.count() == 0
-def test_add_tiger_data_bad_file(def_config, tiger_table, tokenizer_mock,
+@pytest.mark.asyncio
+async def test_add_tiger_data_bad_file(def_config, tiger_table, tokenizer_mock,
tmp_path):
sqlfile = tmp_path / '1010.csv'
sqlfile.write_text("""Random text""")
- tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
assert tiger_table.count() == 0
-def test_add_tiger_data_hnr_nan(def_config, tiger_table, tokenizer_mock,
+@pytest.mark.asyncio
+async def test_add_tiger_data_hnr_nan(def_config, tiger_table, tokenizer_mock,
csv_factory, tmp_path):
csv_factory('file1', hnr_from=99)
csv_factory('file2', hnr_from='L12')
csv_factory('file3', hnr_to='12.4')
- tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tmp_path), def_config, 1, tokenizer_mock())
assert tiger_table.count() == 1
- assert tiger_table.row()['start'] == 99
+ assert tiger_table.row().start == 99
@pytest.mark.parametrize("threads", (1, 5))
-def test_add_tiger_data_tarfile(def_config, tiger_table, tokenizer_mock,
+@pytest.mark.asyncio
+async def test_add_tiger_data_tarfile(def_config, tiger_table, tokenizer_mock,
tmp_path, src_dir, threads):
tar = tarfile.open(str(tmp_path / 'sample.tar.gz'), "w:gz")
tar.add(str(src_dir / 'test' / 'testdb' / 'tiger' / '01001.csv'))
tar.close()
- tiger_data.add_tiger_data(str(tmp_path / 'sample.tar.gz'), def_config, threads,
- tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tmp_path / 'sample.tar.gz'), def_config, threads,
+ tokenizer_mock())
assert tiger_table.count() == 6213
-def test_add_tiger_data_bad_tarfile(def_config, tiger_table, tokenizer_mock,
+@pytest.mark.asyncio
+async def test_add_tiger_data_bad_tarfile(def_config, tiger_table, tokenizer_mock,
tmp_path):
tarfile = tmp_path / 'sample.tar.gz'
tarfile.write_text("""Random text""")
with pytest.raises(UsageError):
- tiger_data.add_tiger_data(str(tarfile), def_config, 1, tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tarfile), def_config, 1, tokenizer_mock())
-def test_add_tiger_data_empty_tarfile(def_config, tiger_table, tokenizer_mock,
+@pytest.mark.asyncio
+async def test_add_tiger_data_empty_tarfile(def_config, tiger_table, tokenizer_mock,
tmp_path):
tar = tarfile.open(str(tmp_path / 'sample.tar.gz'), "w:gz")
tar.add(__file__)
tar.close()
- tiger_data.add_tiger_data(str(tmp_path / 'sample.tar.gz'), def_config, 1,
- tokenizer_mock())
+ await tiger_data.add_tiger_data(str(tmp_path / 'sample.tar.gz'), def_config, 1,
+ tokenizer_mock())
assert tiger_table.count() == 0
-# SPDX-License-Identifier: GPL-2.0-only
+# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2022 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for centroid computation.
"""
import pytest
-from nominatim.utils.centroid import PointsCentroid
+from nominatim_db.utils.centroid import PointsCentroid
def test_empty_set():
c = PointsCentroid()
#
# This file is part of Nominatim. (https://nominatim.org)
#
-# Copyright (C) 2023 by the Nominatim developer community.
+# Copyright (C) 2024 by the Nominatim developer community.
# For a full list of authors see the git log.
"""
Tests for the streaming JSON writer.
import pytest
-from nominatim.utils.json_writer import JsonWriter
+from nominatim_api.utils.json_writer import JsonWriter
@pytest.mark.parametrize("inval,outstr", [(None, 'null'),
(True, 'true'), (False, 'false'),
nlohmann-json3-dev postgresql-14-postgis-3 \
postgresql-contrib-14 postgresql-14-postgis-3-scripts \
libicu-dev python3-dotenv \
- python3-psycopg2 python3-psutil python3-jinja2 \
+ python3-pip python3-psutil python3-jinja2 \
python3-sqlalchemy python3-asyncpg \
python3-icu python3-datrie python3-yaml git
+# Some of the Python packages that come with Ubuntu 22.04 are too old,
+# so install the latest version from pip:
+
+ pip3 install --user psycopg[binary]
#
# System Configuration
User=www-data
Group=www-data
WorkingDirectory=$USERHOME/nominatim-project
-ExecStart=$USERHOME/nominatim-venv/bin/gunicorn -b unix:/run/nominatim.sock -w 4 -k uvicorn.workers.UvicornWorker nominatim.server.falcon.server:run_wsgi
+ExecStart=$USERHOME/nominatim-venv/bin/gunicorn -b unix:/run/nominatim.sock -w 4 -k uvicorn.workers.UvicornWorker nominatim_api.server.falcon.server:run_wsgi
ExecReload=/bin/kill -s HUP \$MAINPID
StandardOutput=append:/var/log/gunicorn-nominatim.log
StandardError=inherit
sudo systemctl restart apache2
fi #DOCS:
-# The Nominatim API is now available at `http://localhost/nominatim/`.
+# The Nominatim API is now available at `http://localhost/nominatim/`. Point your browser
+# to the status output `http://localhost/nominatim/status` to test if everything is ok.
fi #DOCS:
sudo systemctl restart nginx
fi #DOCS:
-# The Nominatim API is now available at `http://localhost/nominatim/`.
+# The Nominatim API is now available at `http://localhost/nominatim/`. Point your browser
+# to the status output `http://localhost/nominatim/status` to test if everything is ok.
fi #DOCS:
export DEBIAN_FRONTEND=noninteractive #DOCS:
# *Note:* these installation instructions are also available in executable
-# form for use with vagrant under vagrant/Install-on-Ubuntu-20.sh.
+# form for use with vagrant under vagrant/Install-on-Ubuntu-24.sh.
#
# Installing the Required Software
# ================================
#
-# These instructions expect that you have a freshly installed Ubuntu 20.04.
+# These instructions expect that you have a freshly installed Ubuntu 24.04.
#
# Make sure all packages are up-to-date by running:
#
# Now you can install all packages needed for Nominatim:
- sudo apt-get install -y build-essential cmake g++ libboost-dev libboost-system-dev \
- libboost-filesystem-dev libexpat1-dev zlib1g-dev \
- libbz2-dev libpq-dev liblua5.3-dev lua5.3 lua-dkjson \
- nlohmann-json3-dev postgresql-12-postgis-3 \
- postgresql-contrib-12 postgresql-12-postgis-3-scripts \
- libicu-dev python3-dotenv \
- python3-psycopg2 python3-psutil python3-jinja2 python3-pip \
- python3-icu python3-datrie python3-yaml git
-
-# Some of the Python packages that come with Ubuntu 20.04 are too old, so
-# install the latest version from pip:
-
- pip3 install --user sqlalchemy asyncpg
+ sudo apt-get install -y osm2pgsql postgresql-postgis postgresql-postgis-scripts \
+ pkg-config libicu-dev virtualenv git
#
# ---------------------
#
# Tune the postgresql configuration, which is located in
-# `/etc/postgresql/12/main/postgresql.conf`. See section *Tuning the PostgreSQL database*
+# `/etc/postgresql/16/main/postgresql.conf`. See section *Tuning the PostgreSQL database*
# in [the installation page](../admin/Installation.md#tuning-the-postgresql-database)
# for the parameters to change.
#
# Restart the postgresql service after updating this config file.
if [ "x$NOSYSTEMD" == "xyes" ]; then #DOCS:
- sudo pg_ctlcluster 12 main start #DOCS:
+ sudo pg_ctlcluster 16 main start #DOCS:
else #DOCS:
sudo systemctl restart postgresql
fi #DOCS:
#
if [ "x$1" == "xyes" ]; then #DOCS: :::sh
cd $USERHOME
- git clone --recursive https://github.com/openstreetmap/Nominatim.git
+ git clone https://github.com/openstreetmap/Nominatim.git
cd Nominatim
else #DOCS:
cd $USERHOME/Nominatim #DOCS:
wget -O data/country_osm_grid.sql.gz https://nominatim.org/data/country_grid.sql.gz
fi #DOCS:
-# The code must be built in a separate directory. Create this directory,
-# then configure and build Nominatim in there:
+# Nominatim should be installed in a separate Python virtual environment.
+# Create the virtual environment:
+
+ virtualenv $USERHOME/nominatim-venv
- mkdir $USERHOME/build
- cd $USERHOME/build
- cmake $USERHOME/Nominatim
- make
- sudo make install
+# Now install Nominatim using pip:
-# Nominatim is now ready to use. You can continue with
+ cd $USERHOME/Nominatim
+ $USERHOME/nominatim-venv/bin/pip install packaging/nominatim-db
+
+# Nominatim is now ready to use. The nominatim binary is available at
+# `$USERHOME/venv/bin/nominatim`. If you want to have 'nominatim' in your
+# path, simply activate the virtual environment:
+#
+#DOCS:```sh
+# . $USERHOME/nominatim-venv/bin/activate
+#DOCS:```
+#
+# You can continue with
# [importing a database from OSM data](../admin/Import.md). If you want to set up
# the API frontend first, continue reading.
#
# Setting up the Python frontend
# ==============================
#
-# Some of the Python packages in Ubuntu are too old. Therefore run the
-# frontend from a Python virtualenv with current packages.
+# The Python frontend is contained in the nominatim-api package. To run
+# the API as a webservice, you also need falcon with uvicorn to serve the API.
+# It is generally recommended to run falcon/uvicorn on top of gunicorn.
#
-# To set up the virtualenv, run:
+# To install all packages, run:
#DOCS:```sh
-sudo apt-get install -y virtualenv
-virtualenv $USERHOME/nominatim-venv
-$USERHOME/nominatim-venv/bin/pip install SQLAlchemy PyICU psycopg[binary] \
- psycopg2-binary python-dotenv PyYAML falcon uvicorn gunicorn
+$USERHOME/nominatim-venv/bin/pip install psycopg[binary] falcon uvicorn gunicorn
+cd $USERHOME/Nominatim
+$USERHOME/nominatim-venv/bin/pip install packaging/nominatim-api
#DOCS:```
# Next you need to create a systemd job that runs Nominatim on gunicorn.
User=www-data
Group=www-data
WorkingDirectory=$USERHOME/nominatim-project
-ExecStart=$USERHOME/nominatim-venv/bin/gunicorn -b unix:/run/nominatim.sock -w 4 -k uvicorn.workers.UvicornWorker nominatim.server.falcon.server:run_wsgi
+ExecStart=$USERHOME/nominatim-venv/bin/gunicorn -b unix:/run/nominatim.sock -w 4 -k uvicorn.workers.UvicornWorker nominatim_api.server.falcon.server:run_wsgi
ExecReload=/bin/kill -s HUP \$MAINPID
StandardOutput=append:/var/log/gunicorn-nominatim.log
StandardError=inherit
sudo systemctl enable nominatim.service
fi #DOCS:
-
# Setting up a webserver
# ======================
#
# [during the import process](../admin/Import.md#creating-the-project-directory)
# Already create the project directory itself now:
-
mkdir $USERHOME/nominatim-project
-
+#
# Option 1: Using Apache
# ----------------------
#
if [ "x$2" == "xinstall-apache" ]; then #DOCS:
+#
# First install apache itself and enable the proxy module:
sudo apt-get install -y apache2
sudo a2enmod proxy_http
+#
# To set up proxying for Apache add the following configuration:
#DOCS:```sh
sudo tee /etc/apache2/conf-available/nominatim.conf << EOFAPACHECONF
+
ProxyPass /nominatim "unix:/run/nominatim.sock|http://localhost/"
EOFAPACHECONF
#DOCS:```
# Then enable the configuration and restart apache
#
- sudo a2enconf nominatim
+#DOCS:```sh
+sudo a2enconf nominatim
+#DOCS:```
+
if [ "x$NOSYSTEMD" == "xyes" ]; then #DOCS:
sudo apache2ctl start #DOCS:
else #DOCS:
sudo systemctl restart apache2
fi #DOCS:
-# The Nominatim API is now available at `http://localhost/nominatim/`.
+# The Nominatim API is now available at `http://localhost/nominatim/`. Point your browser
+# to the status output `http://localhost/nominatim/status` to test if everything is ok.
fi #DOCS:
sudo apt-get install -y nginx
+
# Then create a Nginx configuration to forward http requests to that socket.
#DOCS:```sh
sudo systemctl restart nginx
fi #DOCS:
-# The Nominatim API is now available at `http://localhost/`.
-
-
+# The Nominatim API is now available at `http://localhost/nominatim/`. Point your browser
+# to the status output `http://localhost/nominatim/status` to test if everything is ok.
fi #DOCS: