def _do_restore():
        """return the SQL statement to restore a backup of the given database"""
        from logilab.database import get_connection
        dbhost = sys.argv[2]
        dbname = sys.argv[3]
        filename = sys.argv[4]
        sql_server_local_filename = r"C:\Backups\%s" % dbname
        file_share_filename = r"\\%s\Backups\%s" % (dbhost, dbname)
        shutil.copy(filename, file_share_filename)
        cnx = get_connection(driver='sqlserver2005',
                             host=dbhost,
                             database='master',
                             extra_args='autocommit;trusted_connection')

        cursor = cnx.cursor()
        cursor.execute(
            "RESTORE DATABASE %(db)s FROM DISK= %(path)s WITH REPLACE", {
                'db': dbname,
                'path': sql_server_local_filename,
            })
        import time
        sleeptime = 10
        while True:
            time.sleep(sleeptime)
            try:
                cnx = get_connection(driver='sqlserver2005',
                                     host=dbhost,
                                     database=dbname,
                                     extra_args='trusted_connection')
                break
            except:
                sleeptime = min(sleeptime * 2, 300)
        os.remove(file_share_filename)
        sys.exit(0)
示例#2
0
 def run(self, args):
     check_options_consistency(self.config)
     print('\n' + underline_title('Initializing the system database'))
     from cubicweb.server import init_repository
     appid = args[0]
     config = ServerConfiguration.config_for(appid)
     try:
         system = config.system_source_config
         extra_args = system.get('db-extra-arguments')
         extra = extra_args and {'extra_args': extra_args} or {}
         get_connection(system['db-driver'],
                        database=system['db-name'],
                        host=system.get('db-host'),
                        port=system.get('db-port'),
                        user=system.get('db-user') or '',
                        password=system.get('db-password') or '',
                        schema=system.get('db-namespace'),
                        **extra)
     except Exception as ex:
         raise ConfigurationError(
             'You seem to have provided wrong connection information in '
             'the %s file. Resolve this first (error: %s).' %
             (config.sources_file(), str(ex).strip()))
     init_repository(config, drop=self.config.drop)
     if not self.config.automatic:
         while ASK.confirm('Enter another source ?', default_is_yes=False):
             CWCTL.run([
                 'source-add', '--config-level',
                 str(self.config.config_level), config.appid
             ])
示例#3
0
def source_cnx(source, dbname=None, special_privs=False, interactive=True):
    """open and return a connection to the system database defined in the
    given server.serverconfig
    """
    from getpass import getpass
    dbhost = source.get('db-host')
    if dbname is None:
        dbname = source['db-name']
    driver = source['db-driver']
    dbhelper = get_db_helper(driver)
    if interactive:
        print('-> connecting to %s database' % driver, end=' ')
        if dbhost:
            print('%s@%s' % (dbname, dbhost), end=' ')
        else:
            print(dbname, end=' ')
    if dbhelper.users_support:
        if not interactive or (not special_privs and source.get('db-user')):
            user = source.get('db-user', os.environ.get('USER', ''))
            if interactive:
                print('as', user)
            password = source.get('db-password')
        else:
            print()
            if special_privs:
                print('WARNING')
                print('the user will need the following special access rights '
                      'on the database:')
                print(special_privs)
                print()
            default_user = source.get('db-user', os.environ.get('USER', ''))
            user = input('Connect as user ? [%r]: ' % default_user)
            user = user.strip() or default_user
            if user == source.get('db-user'):
                password = source.get('db-password')
            else:
                password = getpass('password: '******'db-extra-arguments')
    extra = extra_args and {'extra_args': extra_args} or {}
    cnx = get_connection(driver,
                         dbhost,
                         dbname,
                         user,
                         password=password,
                         port=source.get('db-port'),
                         schema=source.get('db-namespace'),
                         **extra)
    try:
        cnx.logged_user = user
    except AttributeError:
        # C object, __slots__
        from logilab.database import _SimpleConnectionWrapper
        cnx = _SimpleConnectionWrapper(cnx)
        cnx.logged_user = user
    return cnx
    def test_tzsupport(self):
        cnx = get_connection(database=':memory:', driver='sqlite')
        cu = cnx.cursor()
        cu.execute('CREATE TABLE tztest(tzt tzdatetime)')
        now = datetime.now(tzutc())
        cu.execute('INSERT INTO tztest VALUES (%(tzt)s)', {'tzt': now})
        cu.execute('SELECT * FROM tztest')
        dbnow = cu.fetchone()[0]
        self.assertEqual(dbnow, now)

        cu.execute('UPDATE tztest SET tzt=(%(tzt)s)',
                   {'tzt': datetime.utcnow()})
        cu.execute('SELECT * FROM tztest')
        dbnow = cu.fetchone()[0]
        self.assertEqual(dbnow.tzinfo, tzutc())
 def _do_backup():
     import time
     from logilab.database import get_connection
     dbhost = sys.argv[2]
     dbname = sys.argv[3]
     filename = sys.argv[4]
     cnx = get_connection(driver='sqlserver2005',
                          host=dbhost,
                          database=dbname,
                          extra_args='autocommit;trusted_connection')
     cursor = cnx.cursor()
     sql_server_local_filename = r"C:\Backups\%s" % dbname
     file_share_filename = r"\\%s\Backups\%s" % (dbhost, dbname)
     cursor.execute("BACKUP DATABASE %(db)s TO DISK= %(path)s ", {
         'db': dbname,
         'path': sql_server_local_filename,
     })
     prev_size = -1
     err_count = 0
     same_size_count = 0
     while err_count < 10 and same_size_count < 10:
         time.sleep(1)
         try:
             size = os.path.getsize(file_share_filename)
         except OSError as exc:
             self.logger.exception('error accessing %s',
                                   file_share_filename)
             err_count += 1
         if size > prev_size:
             same_size_count = 0
             prev_size = size
         else:
             same_size_count += 1
     shutil.copy(file_share_filename, filename)
     os.remove(file_share_filename)
     cnx.close()
     sys.exit(0)