Substitute the root dir into the database DSN, for Sqlite
559894
def database_dsn(self):
        """"""

        if not self._config.library.database:
            return 'sqlite:///{root}/library.db'.format(root=self._root)

        return self._config.library.database.format(root=self._root)
714198
def select_directory(self):
        """"""
        basedir = to_text_string(self.wd_edit.text())
        if not osp.isdir(basedir):
            basedir = getcwd_or_home()
        directory = getexistingdirectory(self, _(""), basedir)
        if directory:
            self.wd_edit.setText(directory)
            self.dir = directory
392201
def deploy_db(rollback=False):
    
    if not rollback:

        if env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3':
            db_dir = '/'.join([deployment_root(),'database'])
            db_name = ''.join([env.project_name,'_','site_1','.db'])
            dest_db_path = '/'.join([db_dir,db_name])
            if exists(dest_db_path): return
            if env.verbosity:
                print env.host,"DEPLOYING DEFAULT SQLITE DATABASE"
            if not env.DEFAULT_DATABASE_NAME:
                print "ERROR: A database name has not been defined in your Django settings file"
                sys.exit(1)

            if env.DEFAULT_DATABASE_NAME[0] not in [os.path.sep,'.']: #relative path
                db_path = os.path.join(os.getcwd(),env.project_package_name,env.DEFAULT_DATABASE_NAME)

            elif env.DEFAULT_DATABASE_NAME[:2] == '..':
                print "ERROR: Use a full expanded path to the database in your Django settings"
                sys.exit(1)
            else:
                db_path = env.DEFAULT_DATABASE_NAME

            if not db_path or not os.path.exists(db_path):
                print "ERROR: the database %s does not exist. \nRun python manage.py syncdb to create your database locally first, or check your settings."% db_path
                sys.exit(1)

            db_name = os.path.split(db_path)[1]  
            run('mkdir -p '+db_dir)
            put(db_path,dest_db_path)
            #directory and file must be writable by webserver
            sudo("chown -R %s:www-data %s"% (env.user,db_dir))
            sudo("chmod -R ug+w %s"% db_dir)
        
        elif env.DEFAULT_DATABASE_ENGINE=='django.db.backends.':
            print "ERROR: The default database engine has not been defined in your Django settings file"
            print "At a minimum you must define an sqlite3 database for woven to deploy, or define a database that is managed outside of woven."
            sys.exit(1)
    elif rollback and env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3':
        if env.INTERACTIVE:
            delete = confirm('DELETE the database on the host?',default=False)
            if delete:
                run('rm -f '+db_name)
    return
1361716
def db_create(cls, impl, working_dir):
        

        global VIRTUALCHAIN_DB_SCRIPT
       
        log.debug("Setup chain state in {}".format(working_dir))

        path = config.get_snapshots_filename(impl, working_dir)
        if os.path.exists( path ):
            raise Exception("Database {} already exists")

        lines = [l + ";" for l in VIRTUALCHAIN_DB_SCRIPT.split(";")]
        con = sqlite3.connect(path, isolation_level=None, timeout=2**30)

        for line in lines:
            con.execute(line)

        con.row_factory = StateEngine.db_row_factory
        return con
178628
def _normalize_dir(string_):
    '''
    
    '''
    return os.path.normpath(salt.utils.stringutils.to_unicode(string_))
785124
def _dbdir():
    
    global dbdir
    from os import mkdir, path, getcwd, chdir
    
    if dbdir is None:
        from acorn.config import settings
        config = settings("acorn")
        if (config.has_section("database") and
            config.has_option("database", "folder")):
            dbdir = config.get("database", "folder")
        else: # pragma: no cover
            raise ValueError("The folder to save DBs in must be configured"
                             "  in 'acorn.cfg'")

    #It is possible to specify the database path relative to the repository
    #root. path.abspath will map it correctly if we are in the root directory.
    from acorn.utility import abspath
    if not path.isabs(dbdir):
        #We want absolute paths to make it easier to port this to other OS.
        dbdir = abspath(dbdir)
        
    if not path.isdir(dbdir): # pragma: no cover
        mkdir(dbdir)
        
    return dbdir
248725
def _compose(self, name, args, mkdir=True):
        """"""
        from os.path import normpath
        from ambry.dbexceptions import ConfigurationError

        root = p = self._config.filesystem[name].format(root=self._root)

        if args:
            args = [e.strip() for e in args]
            p = join(p, *args)

        if not isdir(p) and mkdir:
            makedirs(p)

        p = normpath(p)

        if not p.startswith(root):
            raise ConfigurationError("Path for name='{}', args={} resolved outside of define filesystem root"
                                 .format(name, args))

        return p
602553
function _db(dbConfig, dataPath) {
  if (dbConfig.dialect === 'sqlite') {
    /* eslint-disable-next-line no-param-reassign */
    dbConfig.storage = resolve(dataPath, 'vapid.sqlite');
  }

  return new Database(dbConfig);
}
365215
function rmdirRecursive(root, chunks, callback) {

  var chunk = chunks.pop();
  if (!chunk) {
    return callback(null);
  }
  var pathname = path.join(root, '..'); // backtrack

  return fs.exists(root, function(exists) {

    if (exists === false) { // already done
      return rmdirRecursive(root, chunks, callback);
    }
    return fs.rmdir(root, function(err) {

      if (err) {
        return callback(err);
      }
      return rmdirRecursive(pathname, chunks, callback); // let's magic
    });
  });
}
1098230
def db_url_from_hass_config(path):
    """"""
    config = load_hass_config(path)
    default_path = os.path.join(path, "home-assistant_v2.db")
    default_url = "sqlite:///{}".format(default_path)

    recorder = config.get("recorder")

    if recorder:
        db_url = recorder.get("db_url")
        if db_url is not None:
            return db_url

    if not os.path.isfile(default_path):
        raise ValueError(
            "Unable to determine DB url from hass config at {}".format(path)
        )

    return default_url
470131
def _update_dirs_on_base(self):
        ''''''
        if self._dirs['base'] != None:
            for d in self._predefined_dir_names:
                dstr = d
                #if d == "s2":
                #    dstr = '.'+d
                self._dirs[d] = os.path.join(self._dirs['base'], dstr)
266320
def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]):
    """"""
    if value:
        return value

    if ctx.params["repository"]:
        return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE)

    raise click.BadParameter("Could not guess a database location")
770316
def get_db_uri(config, output_dir):
    
    db_config = config.get("results_database", {"db_uri": "default"})
    if db_config['db_uri'] == 'default':
        return os.path.join(output_dir, "results.sqlite")
    return db_config['db_uri']
449046
def mount(location, access='rw', root=None):
    '''
    
    '''
    if root is None:
        root = os.path.join(
            tempfile.gettempdir(),
            'guest',
            location.lstrip(os.sep).replace('/', '.')
        )
        log.debug('Using root %s', root)
    if not os.path.isdir(root):
        try:
            os.makedirs(root)
        except OSError:
            # Somehow the path already exists
            pass
    while True:
        if os.listdir(root):
            # Stuff is in there, don't use it
            hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
            rand = hash_type(os.urandom(32)).hexdigest()
            root = os.path.join(
                tempfile.gettempdir(),
                'guest',
                location.lstrip(os.sep).replace('/', '.') + rand
            )
            log.debug('Establishing new root as %s', root)
        else:
            break
    cmd = 'guestmount -i -a {0} --{1} {2}'.format(location, access, root)
    __salt__['cmd.run'](cmd, python_shell=False)
    return root
129560
def put(self, key, value):
    '''
    '''
    super(DirectoryTreeDatastore, self).put(key, value)

    str_key = str(key)

    # ignore root
    if str_key == '/':
      return

    # retrieve directory, to add entry
    dir_key = key.parent.instance('directory')
    directory = self.directory(dir_key)

    # ensure key is in directory
    if str_key not in directory:
      directory.append(str_key)
      super(DirectoryTreeDatastore, self).put(dir_key, directory)
1260661
function mkdir(root, mode, callback) {

  if (typeof mode === 'function') {
    var callback = mode;
    var mode = null;
  }
  if (typeof root !== 'string') {
    throw new Error('missing root');
  } else if (typeof callback !== 'function') {
    throw new Error('missing callback');
  }

  var chunks = root.split(path.sep); // split in chunks
  var chunk;
  if (path.isAbsolute(root) === true) { // build from absolute path
    chunk = chunks.shift(); // remove "/" or C:/
    if (!chunk) { // add "/"
      chunk = path.sep;
    }
  } else {
    chunk = path.resolve(); // build with relative path
  }

  return mkdirRecursive(chunk, chunks, mode, callback);
}
313850
function replaceStringsInFile(name, rootDir, replacements) {
  return findFirstFile(name, rootDir)
  .then(function (path) {
    return fs.readFileAsync(path, 'utf8')
    .then(function (content) {
      return replaceContent(path, content, replacements);
    })
    .then(function (content) {
      return fs.writeFileAsync(path, content, 'utf8');
    });

  })
  .catch(function (error) {
    console.error(
      'we couldn\'t replace strings in file, error: \'%s\', stack: \'%s\'',
      error.toString(), error.stack
    );
    return Promise.reject(error);
  });
}