Python peewee.SqliteDatabase() Examples

The following are 30 code examples of peewee.SqliteDatabase(). 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 peewee , or try the search function .
Example #1
Source File: fake_item_ids.py    From detdup with MIT License 6 votes vote down vote up
def __init__(self, data_model):
        self.data_model = data_model
        self.data_model.fake_item_ids_store = self

        assert self.data_model.cache_dir, "FakeItemIds need cache_dir from data_model!"
        sqlite_path = os.path.join(self.data_model.cache_dir, "fake_item_ids_store.db")

        sqlite_database = SqliteDatabase(sqlite_path, check_same_thread=False)

        class FakeItemIdsStore(Model):
            is_deleted = BooleanField(default=False)  # mark processed or duplicated items
            item_id = CharField()
            item_content_json = TextField()
            created_at = TimeField(default=datetime.datetime.now)

            class Meta:
                database = sqlite_database
        self.storage = FakeItemIdsStore

        if not self.storage.table_exists():
            self.storage.create_table()
            sqlite_database.create_index(self.storage, "is_deleted item_id".split(" ")) 
Example #2
Source File: app.py    From conducthotline.com with Apache License 2.0 6 votes vote down vote up
def apply_migration(step):
    import peewee
    import playhouse.migrate
    from hotline.database import models

    migrations_module = importlib.import_module(
        f".{step}", package="hotline.database.migrations"
    )

    if isinstance(models.db.obj, peewee.SqliteDatabase):
        migrator = playhouse.migrate.SqliteMigrator(models.db)
    else:
        migrator = playhouse.migrate.PostgresqlMigrator(models.db)

    migrations = migrations_module.migrate(migrator)

    print(f"The following migrations are about to be applied to {models.db.obj}:")
    for migration in migrations:
        print(" * ", migration.method, migration.args)

    input("Press enter to continue.")

    playhouse.migrate.migrate(*migrations)

    print("Done.") 
Example #3
Source File: database.py    From mqtt-pwn with GNU General Public License v3.0 6 votes vote down vote up
def create_db_connection():
    """ Creates a database connection with the postgres db"""

    is_test_env = os.getenv('MQTT_PWN_TESTING_ENV')

    if is_test_env:
        db = SqliteDatabase(':memory:')
    else:
        db = PostgresqlDatabase(
            config.DB_NAME,
            user=config.DB_USER,
            password=config.DB_PASSWORD,
            host=config.DB_HOST,
            port=config.DB_PORT
        )

    database_proxy.initialize(db)

    return db 
Example #4
Source File: 006_packageversion_license_textfield.py    From pypi-server with MIT License 6 votes vote down vote up
def change_license_field_type(migrator, db):
    if isinstance(db, peewee.SqliteDatabase):
        # SQLite has not length
        return

    try:
        migrate(migrator.drop_column('packageversion', 'license_old'))
    except:
        pass

    with db.transaction():
        migrate(
            migrator.rename_column('packageversion', 'license', 'license_old'),
            migrator.add_column("packageversion", 'license', PackageVersion.license),
        )

        db.execute_sql("UPDATE packageversion SET license = license_old")
        migrate(migrator.drop_column('packageversion', 'license_old')) 
Example #5
Source File: migrator.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def __get_migrator(self):
		if isinstance(self.db.engine, peewee.SqliteDatabase) or isinstance(self.db.engine, SqliteExtDatabase):
			return SqliteMigrator(self.db.engine)
		elif isinstance(self.db.engine, peewee.MySQLDatabase):
			return MySQLMigrator(self.db.engine)
		elif isinstance(self.db.engine, peewee.PostgresqlDatabase):
			return PostgresqlMigrator(self.db.engine)
		raise ImproperlyConfigured('Database engine doesn\'t support Migrations!') 
Example #6
Source File: fixtures.py    From quay with Apache License 2.0 5 votes vote down vote up
def _init_db_path_sqlite(tmpdir_factory):
    """
    Initializes a SQLite database for testing by populating it from scratch and placing it into a
    temp directory file.
    """
    sqlitedbfile = str(tmpdir_factory.mktemp("data").join("test.db"))
    sqlitedb = "sqlite:///{0}".format(sqlitedbfile)
    conf = {
        "TESTING": True,
        "DEBUG": True,
        "SECRET_KEY": "superdupersecret!!!1",
        "DATABASE_SECRET_KEY": "anothercrazykey!",
        "DB_URI": sqlitedb,
    }
    os.environ["DB_URI"] = str(sqlitedb)
    db.initialize(SqliteDatabase(sqlitedbfile))
    application.config.update(conf)
    application.config.update({"DB_URI": sqlitedb})
    initialize_database()

    db.obj.execute_sql("PRAGMA foreign_keys = ON;")
    db.obj.execute_sql('PRAGMA encoding="UTF-8";')

    populate_database()
    close_db_filter(None)
    return str(sqlitedbfile) 
Example #7
Source File: database.py    From scylla with Apache License 2.0 5 votes vote down vote up
def create_connection() -> SqliteDatabase:
    """
    create a database connection
    :rtype: SqliteDatabase
    """
    global _db
    if _db:
        return _db
    else:
        logger.debug('create new db connection')
        _db = SqliteDatabase(get_config('db_path', './scylla.db'))
        return _db 
Example #8
Source File: orm.py    From pyscp with MIT License 5 votes vote down vote up
def connect(dbpath):
    log.info('Connecting to the database at {}'.format(dbpath))
    db.initialize(peewee.SqliteDatabase(dbpath))
    db.connect()


###############################################################################
# Macros
############################################################################### 
Example #9
Source File: peeweedbevolve.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_sqlite(db):
  return isinstance(db, pw.SqliteDatabase) 
Example #10
Source File: test.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_create_table_other_schema(self):
    self.db.execute_sql('create schema other_schema;')
    class SomeModel(pw.Model):
      some_field = pw.CharField(null=True)
      class Meta:
        database = self.db
        schema = 'other_schema'
    self.evolve_and_check_noop(schema='other_schema')
    SomeModel.create(some_field='woot')
    self.assertEqual(SomeModel.select().first().some_field, 'woot')




## SQLite doesn't work
#class SQLite(PostgreSQL):
#  @classmethod
#  def setUpClass(cls):
#    os.system('rm /tmp/peeweedbevolve_test.db')
#
#  def setUp(self):
#    self.db = pw.SqliteDatabase('/tmp/peeweedbevolve_test.db')
#    self.db.connect()
#    peeweedbevolve.clear()
#
#  def tearDown(self):
#    self.db.close()
#    os.system('rm /tmp/peeweedbevolve_test.db') 
Example #11
Source File: file_lister_peewee.py    From Learning-Python-for-Forensics-Second-Edition with MIT License 5 votes vote down vote up
def init_db(db):
    """
    The init_db function opens or creates the database
    :param db_path: The file path for the database
    :return: conn, the sqlite3 database connection
    """
    database = peewee.SqliteDatabase(db)
    database_proxy.initialize(database)
    table_list = [Custodians, Files]  # Update with any new tables
    database.create_tables(table_list, safe=True) 
Example #12
Source File: test_cli.py    From tracboat with GNU General Public License v3.0 5 votes vote down vote up
def test_migrate(export_file, tmpdir):
    runner = CliRunner()
    memory_db = peewee.SqliteDatabase(':memory:')
    migrate_mock = mock.MagicMock(spec=migrate.migrate, side_effect=migrate.migrate)
    with mock.patch('tracboat.cli.peewee.SqliteDatabase', lambda uri: memory_db), \
         mock.patch('tracboat.migrate.migrate', migrate_mock):
        result = runner.invoke(
            cli.migrate, obj={}, catch_exceptions=False,
            args=['--from-export-file', export_file, '--mock', '--mock-path', str(tmpdir)]
        )
        migrate_mock.assert_called()
        assert result.exit_code == 0 
Example #13
Source File: database.py    From paper-to-git with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.path = None
        self.db = SqliteDatabase(None) 
Example #14
Source File: PWDatabase.py    From neo-python with MIT License 5 votes vote down vote up
def __init__(self, path):
        try:
            self._db = SqliteDatabase(path, check_same_thread=False)
            PWDatabase.DBProxy().initialize(self._db)
            self.startup()
        except Exception as e:
            logger.error("database file does not exist, or incorrect permissions") 
Example #15
Source File: conftest.py    From sanic_crud with MIT License 5 votes vote down vote up
def app(request):
    from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField
    from sanic import Sanic
    from sanic.log import log

    from sanic_crud import generate_crud

    db = SqliteDatabase('tests/test.db')

    class BaseModel(Model):
        class Meta:
            database = db

    class Job(BaseModel):
        name = CharField()
        description = CharField()
        base_pay = IntegerField()

    class Person(BaseModel):
        name = CharField()
        job = ForeignKeyField(Job, related_name='person_job', null=True)
        email = CharField()

    db.create_tables([Person, Job])
    job = Job(name='Space garbage man', description='Collects garbage in space', base_pay=15)
    person = Person(name='Sanic the Hedgehog', email='gottagofeast@fast.com', job=1)
    job.save()
    person.save()

    test_app = Sanic(__name__)

    test_app.log = log
    generate_crud(test_app, [Person, Job])

    def final():
        db.drop_tables([Person, Job])

    request.addfinalizer(final)
    return test_app 
Example #16
Source File: generator.py    From series-tiempo-ar-api with MIT License 5 votes vote down vote up
def __enter__(self):
        if os.path.exists(self.name):
            os.remove(self.name)

        self.db = peewee.SqliteDatabase(self.name)
        proxy.initialize(self.db)
        self.db.create_tables([Metadatos, Valores, Fuentes])

        return self.db 
Example #17
Source File: sql_generator_tests.py    From series-tiempo-ar-api with MIT License 5 votes vote down vote up
def init_db(self):
        files = DumpFile.get_last_of_type(DumpFile.TYPE_SQL, node=None)

        self.assertTrue(files)

        sql_dump_file = files[0]
        f = NamedTemporaryFile(delete=False)
        f.write(sql_dump_file.file.read())
        f.seek(0)
        f.close()
        proxy.initialize(peewee.SqliteDatabase(f.name))
        proxy.create_tables([Metadatos], safe=True) 
Example #18
Source File: initdb.py    From quay with Apache License 2.0 5 votes vote down vote up
def wipe_database():
    logger.debug("Wiping all data from the DB.")

    # Sanity check to make sure we're not killing our prod db
    if not IS_TESTING_REAL_DATABASE and not isinstance(db.obj, SqliteDatabase):
        raise RuntimeError("Attempted to wipe production database!")

    db.drop_tables(all_models) 
Example #19
Source File: test.py    From slim with zlib License 5 votes vote down vote up
def get_peewee_db():
    """
    Get peewee database instance
    :return:
    """
    db = SqliteDatabase(":memory:")
    return db 
Example #20
Source File: schema.py    From taxadb with MIT License 5 votes vote down vote up
def get_database(self):
        """Returns the correct database driver

        Returns:
            :obj:`pw.Database`
        Raises:
            AttributeError: if `--username` or `--password` not passed
                (if `--dbtype [postgres|mysql]`)

        """
        if self.get('dbtype') == 'sqlite':
            return pw.SqliteDatabase(self.get('dbname'),
                                     pragmas={'journal_mode': 'wal',
                                              'cache_size': -1 * 64000})
        else:
            if self.get('username') is None or self.get('password') is None:
                raise AttributeError('[ERROR] dbtype %s requires username and'
                                     ' password.\n' % str(self.get('dbtype')))
            if self.get('hostname') is None:
                self.set('hostname', 'localhost')
            if self.get('dbtype') == 'mysql':
                if self.get('port') is None or self.get('port') == '':
                    self.set('port', str(3306))
                return pw.MySQLDatabase(
                    self.get('dbname'),
                    user=self.get('username'),
                    password=self.get('password'),
                    host=self.get('hostname'),
                    port=int(self.get('port')))
            elif self.get('dbtype') == 'postgres':
                if self.get('port') is None or self.get('port') == '':
                    self.set('port', str(5432))
                return pw.PostgresqlDatabase(
                    self.get('dbname'),
                    user=self.get('username'),
                    password=self.get('password'),
                    host=self.get('hostname'),
                    port=int(self.get('port'))) 
Example #21
Source File: conftest.py    From vorta with GNU General Public License v3.0 5 votes vote down vote up
def qapp(tmpdir_factory, local_en):
    tmp_db = tmpdir_factory.mktemp('Vorta').join('settings.sqlite')
    mock_db = peewee.SqliteDatabase(str(tmp_db))
    vorta.models.init_db(mock_db)

    from vorta.application import VortaApp
    VortaApp.set_borg_details_action = MagicMock()  # Can't use pytest-mock in session scope
    VortaApp.scheduler = MagicMock()

    qapp = VortaApp([])  # Only init QApplication once to avoid segfaults while testing.

    yield qapp 
Example #22
Source File: __main__.py    From vorta with GNU General Public License v3.0 5 votes vote down vote up
def main():
    args = parse_args()
    signal.signal(signal.SIGINT, signal.SIG_DFL)  # catch ctrl-c and exit

    want_version = getattr(args, 'version', False)
    want_background = getattr(args, 'daemonize', False)

    if want_version:
        print(f"Vorta {__version__}")
        sys.exit()

    if want_background:
        if os.fork():
            sys.exit()

    init_logger(background=want_background)

    # Init database
    sqlite_db = peewee.SqliteDatabase(os.path.join(SETTINGS_DIR, 'settings.db'))
    init_db(sqlite_db)

    # Init app after database is available
    from vorta.application import VortaApp
    app = VortaApp(sys.argv, single_app=True)
    app.updater = get_updater()

    sys.exit(app.exec_()) 
Example #23
Source File: __init__.py    From pypi-server with MIT License 5 votes vote down vote up
def init_sqlite(url):
    global DB

    dbfile = os.path.join("/", *url.path.split("/"))
    dirname = os.path.dirname(dbfile)

    log.info('Opening sqlite database: %s', dbfile)

    if not os.path.exists(dirname):
        os.makedirs(dirname)

    DB.initialize(SqliteDatabase(dbfile))
    log.info("Database initialized as '%s'. Checking migrations...", dbfile)
    return DB, SqliteMigrator(DB) 
Example #24
Source File: store.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def _create_database(self):
        return SqliteDatabase(
            self.database_path, pragmas={"foreign_keys": 1, "secure_delete": 1}
        ) 
Example #25
Source File: models.py    From ga4gh-server with Apache License 2.0 5 votes vote down vote up
def __init__(self, *_, **__):
        super(SqliteDatabase, self).__init__(*_, **__) 
Example #26
Source File: config.py    From sentinel with MIT License 5 votes vote down vote up
def get_db_conn():
    import peewee
    env = os.environ.get('SENTINEL_ENV', 'production')

    # default values should be used unless you need a different config for development
    db_host = sentinel_cfg.get('db_host', '127.0.0.1')
    db_port = sentinel_cfg.get('db_port', None)
    db_name = sentinel_cfg.get('db_name', 'sentinel')
    db_user = sentinel_cfg.get('db_user', 'sentinel')
    db_password = sentinel_cfg.get('db_password', 'sentinel')
    db_charset = sentinel_cfg.get('db_charset', 'utf8mb4')
    db_driver = sentinel_cfg.get('db_driver', 'sqlite')

    if (env == 'test'):
        if db_driver == 'sqlite':
            db_name = sqlite_test_db_name(db_name)
        else:
            db_name = "%s_test" % db_name

    peewee_drivers = {
        'mysql': peewee.MySQLDatabase,
        'postgres': peewee.PostgresqlDatabase,
        'sqlite': peewee.SqliteDatabase,
    }
    driver = peewee_drivers.get(db_driver)

    dbpfn = 'passwd' if db_driver == 'mysql' else 'password'
    db_conn = {
        'host': db_host,
        'user': db_user,
        dbpfn: db_password,
    }
    if db_port:
        db_conn['port'] = int(db_port)

    if driver == peewee.SqliteDatabase:
        db_conn = {}

    db = driver(db_name, **db_conn)

    return db 
Example #27
Source File: conftest.py    From restatic with GNU General Public License v3.0 5 votes vote down vote up
def app(tmpdir, qtbot):
    tmp_db = tmpdir.join("settings.sqlite")
    mock_db = peewee.SqliteDatabase(str(tmp_db))
    restatic.models.init_db(mock_db)
    app = RestaticApp([])
    qtbot.addWidget(app.main_window)
    return app 
Example #28
Source File: __main__.py    From restatic with GNU General Public License v3.0 5 votes vote down vote up
def main():

    # Init database
    dbpath = os.path.join(SETTINGS_DIR, "settings.db")
    print("Using database " + dbpath)
    sqlite_db = peewee.SqliteDatabase(dbpath)
    init_db(sqlite_db)

    app = RestaticApp(sys.argv, single_app=True)
    app.updater = get_updater()
    sys.exit(app.exec_()) 
Example #29
Source File: test_peewee.py    From nplusone with MIT License 5 votes vote down vote up
def db():
    return pw.SqliteDatabase(':memory:') 
Example #30
Source File: conftest.py    From selfmailbot with MIT License 5 votes vote down vote up
def db():
    return pw.SqliteDatabase(':memory:')