Monday, March 2, 2020

macOS: add PYTHONPATH to PostgreSQL brew service

Source: Changing the Homebrew Apache PATH variable.

Let's suppose we installed Python requests module.
On my system, requests has been installed in /usr/local/lib/python2.7/site-packages/.
Then, trying to import it from postgres like in
create or replace function tutu(o_status out int) as
$$
import sys, os
import requests, json
plpy.info(sys.version)
plpy.info(sys.path)
return (500)
$$ language plpython2u security definer;
will cause
select * from tutu()
to output
Query 1 ERROR: ERROR:  ImportError: No module named requests
By default, postgres will look in /Library/Python/2.7/site-packages/.
We then need to update PYTHONPATH.
With brew starting postgres, we will update the postgres plist file.
[jerome@jeroboam] > vi /usr/local/opt/postgresql\@9.4/homebrew.mxcl.postgresql\@9.4.plist


  KeepAlive
  
  Label
  homebrew.mxcl.postgresql@9.4
  EnvironmentVariables
  
    PYTHONPATH
    /usr/local/lib/python2.7/site-packages
  
  ProgramArguments
  
    /usr/local/opt/postgresql@9.4/bin/postgres
    -D
    /usr/local/var/postgresql@9.4
  
  RunAtLoad
  
  WorkingDirectory
  /usr/local
  StandardErrorPath
  /usr/local/var/log/postgresql@9.4.log


Then
[jerome@jeroboam] > brew services stop postgresql@9.4
[jerome@jeroboam] > brew services start postgresql@9.4
Then
select * from tutu()
outputs
INFO:  2.7.16 (default, Dec 13 2019, 18:00:32) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s
INFO:  ['/usr/local/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Users/jerome/Library/Python/2.7/lib/python/site-packages', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC']