Python sqlalchemy_utils.database_exists() Examples
The following are 30
code examples of sqlalchemy_utils.database_exists().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sqlalchemy_utils
, or try the search function
.
Example #1
Source File: database.py From choochoo with GNU General Public License v2.0 | 6 votes |
def delete(uri, sys): try: if database_exists(uri): log.debug(f'Deleting database at {uri}') uri_parts = urisplit(uri) if uri_parts.scheme == SQLITE: path = clean_path(uri_parts.path) log.warning(f'Deleting {path}') unlink(path) elif uri_parts.scheme == POSTGRESQL: drop_database(uri) else: raise Exception(f'Unsupported URI {uri}') else: log.warning(f'No database at {uri} (so not deleting)') finally: sys.delete_constant(SystemConstant.DB_URI) sys.delete_constant(SystemConstant.DB_VERSION)
Example #2
Source File: db.py From opensips-cli with GNU General Public License v3.0 | 6 votes |
def exists(self, db=None): """ check for existence of a database object """ check_db = db if db is not None else self.db_name # TODO: do this only for SQLAlchemy if not self.__conn: return False database_url = self.set_url_db(self.db_url, check_db) logger.debug("check database URL '{}'".format(database_url)) try: if sqlalchemy_utils.database_exists(database_url): logger.debug("DB '{}' exists".format(check_db)) return True except sqlalchemy.exc.NoSuchModuleError as me: logger.error("cannot check if database {} exists: {}". format(check_db, me)) raise osdbError("cannot handle {} dialect". format(self.dialect)) from None logger.debug("DB does not exist") return False
Example #3
Source File: import_.py From choochoo with GNU General Public License v2.0 | 6 votes |
def infer_uri(base, source, engine, sys): if ':' in source: if engine: raise Exception(f'Do not specify engine with (what looks like) a URI') uri = source elif len(source) < 8: if not engine: current = sys.get_constant(SystemConstant.DB_URI, none=True) if not current: raise Exception(f'Specify {mm(SQLITE)} or {mm(POSTGRESQL)}') engine = scheme(current) if engine == SQLITE: uri = sqlite_uri(base, version=source) elif engine == POSTGRESQL: uri = postgresql_uri(version=source) else: raise Exception(f'Unknown engine {engine}') else: raise Exception(f'Unexpected version or URI {source}') if database_exists(uri): return uri else: raise Exception(f'No database at {uri}')
Example #4
Source File: db.py From BentoML with Apache License 2.0 | 6 votes |
def init_db(db_url): from sqlalchemy_utils import database_exists extra_db_args = {'echo': True} if is_sqlite_db(db_url): extra_db_args['connect_args'] = {'check_same_thread': False} extra_db_args['echo'] = False engine = create_engine(db_url, **extra_db_args) if not database_exists(engine.url) and not is_sqlite_db(db_url): raise BentoMLException( f'Database does not exist or Database name is missing in config ' f'db.url: {db_url}' ) create_all_or_upgrade_db(engine, db_url) return sessionmaker(bind=engine)
Example #5
Source File: conftest.py From FlowKit with Mozilla Public License 2.0 | 6 votes |
def postgres_test_db(): """ Fixture to yield a PostgreSQL database to be used in the unit tests. The database will only be created once per test session, but the workflow_runs table will be cleared for each test. """ postgres_test_db = testing.postgresql.Postgresql() engine = create_engine(postgres_test_db.url()) from sqlalchemy_utils import database_exists, create_database if not database_exists(engine.url): create_database(engine.url) Base.metadata.create_all(bind=engine, tables=[WorkflowRuns.__table__]) yield postgres_test_db postgres_test_db.stop()
Example #6
Source File: conftest.py From flask-security with MIT License | 6 votes |
def _setup_realdb(realdburl): """ Called when we want to run unit tests against a real DB. This is useful since different DB drivers are pickier about queries etc (such as pyscopg2 and postgres) """ from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database db_name = "flask_security_test_%s" % str(time.time()).replace(".", "_") db_uri = realdburl + db_name engine = create_engine(db_uri) if not database_exists(engine.url): create_database(engine.url) print("Setting up real DB at " + db_uri) return db_uri, {"engine": engine}
Example #7
Source File: admin.py From FeatureHub with MIT License | 6 votes |
def __init__(self, database="featurehub"): """Create the ORMManager and connect to DB. Parameters ---------- database : str, optional (default="featurehub") Name of database within DBMS. """ self.__orm = ORMManager(database) if not database_exists(self.__orm.engine.url): print("Database {} does not exist.".format(database), file=sys.stderr) print("You might want to create it by calling set_up method", file=sys.stderr)
Example #8
Source File: admin.py From FeatureHub with MIT License | 5 votes |
def set_up(self, drop=False): """Create a new DB and create the initial scheme. If the database exists and drop=True, the existing database is dropped and recreated. Regardless, any tables defined by the schema that do not exist are created. Parameters ---------- drop : bool, optional (default=False) Drop database if it already exists. """ # todo extract database name from engine url and report for brevity engine = self.__orm.engine if database_exists(engine.url): print("Database {} already exists.".format(engine.url)) if drop: print("Dropping old database {}".format(engine.url)) drop_database(engine.url) with possibly_talking_action("Re-creating database..."): create_database(engine.url) else: with possibly_talking_action("Creating database..."): create_database(engine.url) with possibly_talking_action("Creating tables..."): Base.metadata.create_all(engine) print("Database {} created successfully".format(engine.url))
Example #9
Source File: ghost.py From ghost with Apache License 2.0 | 5 votes |
def init(self): if self._local_path: dirname = os.path.dirname(self._local_path) if dirname and not os.path.isdir(dirname): os.makedirs(dirname) if not database_exists(self.db.url): create_database(self.db.url) # More on connection strings for sqlalchemy: # http://docs.sqlalchemy.org/en/latest/core/engines.html self.metadata.bind = self.db self.metadata.create_all()
Example #10
Source File: ghost.py From ghost with Apache License 2.0 | 5 votes |
def is_initialized(self): return database_exists(self.db.url)
Example #11
Source File: db.py From opensips-cli with GNU General Public License v3.0 | 5 votes |
def connect(self, db_name=None): """ connect to database """ if db_name is not None: self.db_name = db_name # TODO: do this only for SQLAlchemy try: if self.dialect == "postgres": self.db_url = self.set_url_db(self.db_url, self.db_name) if sqlalchemy_utils.database_exists(self.db_url) is True: engine = sqlalchemy.create_engine(self.db_url, isolation_level='AUTOCOMMIT') if self.__conn: self.__conn.close() self.__conn = engine.connect() # connect the Session object to our engine self.Session.configure(bind=self.__engine) # instanciate the Session object self.session = self.Session() logger.debug("connected to database URL '%s'", self.db_url) else: self.__conn.execute("USE {}".format(self.db_name)) except Exception as e: logger.error("failed to connect to %s", self.db_url) logger.error(e) return False return True
Example #12
Source File: shell.py From app with MIT License | 5 votes |
def reset_db(): if database_exists(DB_URI): drop_database(DB_URI) create_db()
Example #13
Source File: relational_db_api.py From beam-nuggets with MIT License | 5 votes |
def start_session(self): create_if_missing = self._source.create_if_missing is_database_missing = lambda: not database_exists(self._source.url) if create_if_missing and is_database_missing(): create_database(self._source.url) self._session = self._SessionClass()
Example #14
Source File: database.py From choochoo with GNU General Public License v2.0 | 5 votes |
def database_really_exists(uri): try: return database_exists(uri) except Exception: log_current_exception(traceback=False) return False
Example #15
Source File: database.py From choochoo with GNU General Public License v2.0 | 5 votes |
def delete_and_check(uri, force, sys): if force: delete(uri, sys) if database_exists(uri): raise Exception(f'A schema exists at {uri} (use {mm(FORCE)}?)')
Example #16
Source File: database.py From TensorHive with Apache License 2.0 | 5 votes |
def init_db() -> None: '''Creates the database, tables (if they does not exist)''' # Import all modules that define models so that # they could be registered properly on the metadata. from tensorhive.models.User import User from tensorhive.models.Reservation import Reservation from tensorhive.models.RevokedToken import RevokedToken from tensorhive.models.Role import Role from tensorhive.models.Task import Task if not database_exists(DB.SQLALCHEMY_DATABASE_URI): Base.metadata.create_all(bind=engine, checkfirst=True) log.info('[✔] Database created ({path})'.format(path=DB.SQLALCHEMY_DATABASE_URI)) else: log.info('[•] Database found ({path})'.format(path=DB.SQLALCHEMY_DATABASE_URI))
Example #17
Source File: sql_driver.py From multiscanner with Mozilla Public License 2.0 | 5 votes |
def init_db(self): """ Initializes the database connection based on the configuration parameters """ db_type = self.config['db_type'] db_name = self.config['db_name'] if db_type == 'sqlite': # we can ignore host, username, password, etc sql_lite_db_path = os.path.join(os.path.split(CONFIG)[0], db_name) self.db_connection_string = 'sqlite:///{}'.format(sql_lite_db_path) else: username = self.config['username'] password = self.config['password'] host_string = self.config['host_string'] self.db_connection_string = '{}://{}:{}@{}/{}'.format(db_type, username, password, host_string, db_name) self.db_engine = create_engine(self.db_connection_string) # If db not present AND type is not SQLite, create the DB if not self.config['db_type'] == 'sqlite': if not database_exists(self.db_engine.url): create_database(self.db_engine.url) Base.metadata.bind = self.db_engine Base.metadata.create_all() # Bind the global Session to our DB engine global Session Session.configure(bind=self.db_engine)
Example #18
Source File: sqla_queue.py From distributed_framework with Apache License 2.0 | 5 votes |
def __auto_create_database(self): # 'sqlite:////sqlachemy_queues/queues.db' if self._sqla_conn_url.startswith('sqlite:'): if not Path('/sqlachemy_queues').exists(): Path('/sqlachemy_queues').mkdir() else: if not database_exists(self._sqla_conn_url): create_database(self._sqla_conn_url)
Example #19
Source File: base_model.py From eva with Apache License 2.0 | 5 votes |
def init_db(): """Create database if doesn't exist and create all tables.""" engine = SQLConfig().engine if not database_exists(engine.url): LoggingManager().log("Database does not exist, creating database.", LoggingLevel.INFO) create_database(engine.url) LoggingManager().log("Creating tables", LoggingLevel.INFO) BaseModel.metadata.create_all(bind=engine)
Example #20
Source File: database.py From mysql-to-sqlite3 with MIT License | 5 votes |
def __init__(self, database_uri): self.Session = sessionmaker() self.engine = create_engine( database_uri, json_serializer=self.dumps, json_deserializer=json.loads ) if not database_exists(self.engine.url): create_database(self.engine.url) self._create_db_tables() self.Session.configure(bind=self.engine)
Example #21
Source File: dbhelpers.py From zou with GNU Affero General Public License v3.0 | 5 votes |
def create_all(): """ Create all database tables. """ from zou.app import db engine = create_engine(get_db_uri()) if not database_exists(engine.url): create_database(engine.url) return db.create_all()
Example #22
Source File: dbhelpers.py From zou with GNU Affero General Public License v3.0 | 5 votes |
def is_db_exists(): """ Check that database exist. """ engine = create_engine(get_db_uri()) return database_exists(engine.url)
Example #23
Source File: app.py From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_tables(): if not database_exists(DB_NAME): db.create_all() populate_db()
Example #24
Source File: __init__.py From Penny-Dreadful-Tools with GNU General Public License v3.0 | 5 votes |
def __create_schema() -> None: engine = create_engine(APP.config['SQLALCHEMY_DATABASE_URI']) if not database_exists(engine.url): create_database(engine.url) db.DB.create_all() engine.dispose()
Example #25
Source File: main.py From big-album-art with MIT License | 5 votes |
def resetdb_command(): """Destroys and creates the database + tables.""" from sqlalchemy_utils import database_exists, create_database, drop_database if database_exists(DB_URL): print('Deleting database.') drop_database(DB_URL) if not database_exists(DB_URL): print('Creating database.') create_database(DB_URL) #db.drop_all() print('Creating tables.') db.create_all() print('Shiny!')
Example #26
Source File: main.py From big-album-art with MIT License | 5 votes |
def createdb_command(): """Creates the database + tables.""" from sqlalchemy_utils import database_exists, create_database if not database_exists(DB_URL): print('Creating database.') create_database(DB_URL) print('Creating tables.') db.create_all() print('Shiny!')
Example #27
Source File: hammer.py From git-hammer with Apache License 2.0 | 5 votes |
def __init__(self, project_name, database_url=_default_database_url): start_time = datetime.datetime.now() self.project_name = project_name self._engine = create_engine(database_url) self._Session = sessionmaker(bind=self._engine) self._init_properties() if database_exists(self._engine.url): session = self._Session() self._build_repository_map(session) self._build_author_map(session) self._build_commit_map(session) session.close() print('Init time {}'.format(datetime.datetime.now() - start_time))
Example #28
Source File: hammer.py From git-hammer with Apache License 2.0 | 5 votes |
def _ensure_project_exists(self): if not database_exists(self._engine.url): create_database(self._engine.url) Base.metadata.create_all(self._engine) session = self._Session() if not session.query(Project).filter(Project.project_name == self.project_name).first(): project = Project(project_name=self.project_name) session.add(project) session.commit() session.close()
Example #29
Source File: hammer.py From git-hammer with Apache License 2.0 | 5 votes |
def _fail_unless_database_exists(engine): if not database_exists(engine.url): raise DatabaseNotInitializedError('Database must be created for this operation')
Example #30
Source File: shell.py From app with MIT License | 5 votes |
def create_db(): if not database_exists(DB_URI): LOG.debug("db not exist, create database") create_database(DB_URI) # Create all tables # Use flask-migrate instead of db.create_all() flask_migrate.upgrade()