def __init__(self, destination_uri): if not database_exists(destination_uri): while True: database = parse_uri(destination_uri) msg = input( f"The database {database} does not exists, would you like to create it in the destination?(y/n) " ) if msg.lower() == "y": try: create_database(destination_uri) logger.info("Database created..") break except Exception as err: goodby_message(database_not_exists(destination_uri), 1) break elif msg.lower() == "n": goodby_message( "Destination database does not exit \nExiting ..", 0) break print("Please, select command") self.base = automap_base() self.engine = create_engine(destination_uri) # self.base.prepare(self.engine, reflect=True) self.session = Session(self.engine, autocommit=False, autoflush=False)
def postgres(): if database_exists(SQLALCHEMY_DATABASE_URL): drop_database(SQLALCHEMY_DATABASE_URL) create_database(SQLALCHEMY_DATABASE_URL) engine = create_engine( SQLALCHEMY_DATABASE_URL ) TestingSessionLocal = sessionmaker( autocommit=False, autoflush=False, bind=engine) db: Session = TestingSessionLocal() db.execute('create type timerange as range (subtype = time);') db.commit() conn = engine.raw_connection() cur = conn.cursor() psycopg2.extras.register_range( 'timerange', models.TimeRange, cur, globally=True) cur.close() conn.close() models.Base.metadata.create_all(bind=engine) def override_get_db(): try: db = TestingSessionLocal() yield db finally: db.close() app.dependency_overrides[get_db] = override_get_db yield drop_database(SQLALCHEMY_DATABASE_URL)
def __init__(self, source_uri): if not database_exists(source_uri): goodby_message(database_not_exists(source_uri), 0) self.base = automap_base() self.engine = create_engine(source_uri, echo=False) self.base.prepare(self.engine, reflect=True) self.session = Session(self.engine, autocommit=False, autoflush=False)
def db_config(): with open(os.path.join("myproject", "cfg", "config.yml"), "r") as ymlfile: cfg = yaml.load(ymlfile)['database'] engine = create_engine('{0}://{1}:{2}@{3}/{4}'.format( cfg['server'], cfg['user'], cfg['passwd'], cfg['host'], cfg['db'])) if not database_exists(engine.url): create_database(engine.url) return cfg
def db_create(): """Creating database, if it not exists""" if not database_exists(db_credentials): create_database(db_credentials) db.create_all() db.session.commit() print "Successfully created database and tables." else: print "The database already exists!"
def __init__(self, config): self.base = automap_base() if not database_exists(config.destination_uri): while True: msg = input( f"{config.destination_uri} db does not exist, create destination database?(y/n) " ) if msg.lower() == "y": try: create_database(config.destination_uri) print("database creted ..") except Exception as err: goodby_message(err, 1) break elif msg.lower() == "n": goodby_message( "Destination database does not exit \nExiting ..", 0) break print("Please, select command") database_name = parse_uri(config.destination_uri) msg = input( f"The database {database_name} does not exists, would you like to create it in the destination?(y/n) " ) if msg.lower() == "y": try: create_database(config.destination_uri) sys.stdout.write("Database created ..") except Exception as err: print(err) sys.exit(1) else: sys.exit(0) self.engine = create_engine(config.destination_uri) self.base.prepare(self.engine, reflect=True) self.session = Session(self.engine, autocommit=False, autoflush=False)
import os from sqlalchemy_utils.functions.database import create_database, database_exists from models.users import Role, User from models.issues import Attachment, Category, Issue, IssueHistory, Status from manage import db from config import Config #Checking if database exists, and if not -> create it with all tables. db_credentials = Config.db_credentials if 'DATABASE_URL' in os.environ: db_credentials = os.environ['DATABASE_URL'] if not database_exists(db_credentials): create_database(db_credentials) db.create_all() db.session.commit() #Creating some test data. role = Role(role='admin') role1 = Role(role='moderator') role2 = Role(role='user') category = Category(category='road accident', favicon='') category1 = Category(category='infrastructure accident', favicon='') category2 = Category(category='another accident', favicon='') status1 = Status(status="new")
import sqlalchemy as db from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy_utils.functions.database import create_database, database_exists from app import log if os.environ.get("DB_URI"): engine = db.create_engine(os.environ["DB_URI"]) else: engine = db.create_engine( 'mysql+pymysql://admin:[email protected]/favorite' ) if not database_exists(engine.url): create_database(engine.url) Session = sessionmaker(bind=engine) Base = declarative_base() metadata = db.MetaData() metadata.create_all(engine) @contextmanager def session_scope(): """Provide a transactional scope around a series of operations.""" session = Session() try:
from sqlalchemy.dialects.mysql.types import TEXT from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref from sqlalchemy_utils.functions.database import create_database, database_exists # create mysql engine sdb = '10.0.0.3' tdb = '127.0.0.1' engine = create_engine('mysql+pymysql://root:root@' + tdb + '/maintenancedb?charset=utf8', echo=True) metadata = MetaData() # check if database is exists or not # if not exists will be created it if database_exists(engine.url) is False: print("The database is not exists.") print("It's will be created now") create_database(engine.url) else: print("The database already exists.") # create Base Base = declarative_base() class User(Base): __tablename__ = 'users' # name of table # create row's of table id = Column(Integer, primary_key=True, nullable=False)