factory.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. """
  22. Factory to create Database instances
  23. A Generic interface for all DB engines.
  24. Usage:
  25. import pwman.data.factory as DBFactory
  26. db = DBFactory.create(params)
  27. db.open()
  28. .....
  29. """
  30. from pwman.data.database import Database, DatabaseException
  31. import pwman.util.config as config
  32. def check_db_version(type):
  33. if type == "SQLite":
  34. try:
  35. from pwman.data.drivers import sqlite
  36. except ImportError, e:
  37. raise DatabaseException("python-sqlite not installed")
  38. ver = sqlite.check_db_version()
  39. return ver
  40. # TODO: implement version checks for other supported DBs.
  41. def create(type, version=None):
  42. """
  43. create(params) -> Database
  44. Create a Database instance.
  45. 'type' can only be 'SQLite' at the moment
  46. """
  47. if (type == "SQLite"):
  48. try:
  49. from pwman.data.drivers import sqlite
  50. if version == 0.4:
  51. db = sqlite.SQLiteDatabaseNewForm()
  52. else:
  53. db = sqlite.SQLiteDatabase()
  54. except ImportError, e:
  55. raise DatabaseException("python-sqlite not installed")
  56. elif (type == "Postgresql"):
  57. try:
  58. from pwman.data.drivers import postgresql
  59. db = postgresql.PostgresqlDatabase()
  60. except ImportError, e:
  61. raise DatabaseException("python-pygresql not installed")
  62. elif (type == "MySQL"):
  63. try:
  64. from pwman.data.drivers import mysql
  65. db = mysql.MySQLDatabase()
  66. except ImportError, e:
  67. raise DatabaseException("python-mysqldb not installed")
  68. else:
  69. raise DatabaseException("Unknown database type specified")
  70. return db