<commit_before>import sqlite3
import contextlib
from datetime import datetime

import bs4
import requests

URL = 'https://domaintyper.com/top-websites/' \
      'most-popular-websites-with-com-domain'
DB_NAME = 'db.sqlite3'


def fetch_domains():
    """Download most popular domains and write them to file"""
    response = requests.get(URL)
    response.raise_for_status()
    soup = bs4.BeautifulSoup(response.text, 'html.parser')
    return [
        row[1].get_text()
        for row in (
            row.find_all('td')
            for row in soup.table.find_all('tr')
        )
        if len(row) == 3
    ]


def get_db():
    """Opens a new database connection"""
    rv = sqlite3.connect(DB_NAME)
    rv.row_factory = sqlite3.Row
    return rv


def init_db():
    """Initializes the database.
    >>> init_db()
    """
    with contextlib.closing(get_db()) as db:
        cursor = db.cursor()
        with open('schema.sql', mode='r') as file:
            cursor.executescript(file.read())
        cursor.executemany(
            'INSERT INTO records(host, last_refresh) VALUES (?, ?)',
            [(domain, datetime.now().timestamp()) for domain in fetch_domains()]
        )
        db.commit()<commit_msg>feat(db): improve database system<commit_after>import sqlite3
import contextlib

SELECT_LAST_RECORDS = 'SELECT host FROM records WHERE abs(last_refresh - ?) > ?'
UPDATE_RECORDS = 'UPDATE records SET ip=?, last_refresh=? WHERE host=?'
SELECT_PAGED_RECORDS = 'SELECT host, ip FROM records ' \
                       'ORDER BY id LIMIT ? OFFSET ?'


def db(db_name):
    """Opens a new database connection"""
    rv = sqlite3.connect(db_name)
    rv.row_factory = sqlite3.Row
    return rv


def query(_db, _query, *args):
    with contextlib.closing(_db.cursor()) as cursor:
        yield from cursor.execute(_query, args)
{'fraction_non_alphanumeric': 0.12391304347826088, 'fraction_numerical': 0.005978260869565218, 'mean_word_length': 2.8354166666666667, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '426445', 'n_tokens_mistral': 589, 'n_tokens_neox': 566, 'n_words': 148}