From aab93a4d3ef160c446aff8b4d3a9b776cf5e48ce Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Fri, 8 Dec 2023 14:53:17 +0000 Subject: [PATCH] Add FTS with sqlite --- yamdl_playground/core/apps.py | 22 ++++++++++++++++++++++ yamdl_playground/core/views.py | 8 ++++++-- yamdl_playground/settings.py | 2 +- 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 yamdl_playground/core/apps.py diff --git a/yamdl_playground/core/apps.py b/yamdl_playground/core/apps.py new file mode 100644 index 0000000..86fea10 --- /dev/null +++ b/yamdl_playground/core/apps.py @@ -0,0 +1,22 @@ +from django.apps import AppConfig +from django.db import connections +from django.db.models.signals import post_save + +class CoreConfig(AppConfig): + name = "yamdl_playground.core" + + loaded = False + + def ready(self): + if not self.loaded: + connection = connections["default"] + + with connection.cursor() as cursor: + cursor.execute("CREATE VIRTUAL TABLE search_index USING fts5(body);") + + post_save.connect(self.post_save) + self.loaded = True + + def post_save(self, sender, instance, created, **kwargs): + with connections["default"].cursor() as cursor: + cursor.execute("INSERT INTO search_index(body, rowid) VALUES (%s, %s)", [instance.content, instance.pk]) diff --git a/yamdl_playground/core/views.py b/yamdl_playground/core/views.py index 39bcfbc..6e080c0 100644 --- a/yamdl_playground/core/views.py +++ b/yamdl_playground/core/views.py @@ -1,6 +1,10 @@ from .models import Page from django.http import HttpResponse -import os +from django.db import connections def test(request): - return HttpResponse(f"{Page.objects.count()} {os.getpid()}") + with connections["default"].cursor() as cursor: + cursor.execute("SELECT rowid FROM search_index WHERE search_index = %s;", ["content"]) + row = cursor.fetchone() + pages = Page.objects.filter(id__in=row) + return HttpResponse(str(pages), content_type="text/plain") diff --git a/yamdl_playground/settings.py b/yamdl_playground/settings.py index 5856d5b..c6cd25b 100644 --- a/yamdl_playground/settings.py +++ b/yamdl_playground/settings.py @@ -32,8 +32,8 @@ ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.staticfiles', + "yamdl_playground.core", "yamdl", - "yamdl_playground.core" ] MIDDLEWARE = [