#lang cl-yesql/sqlite

-- name: create-stats-table
-- Creates table for tracking visits
CREATE TABLE IF NOT EXISTS STATS (
    timestamp int DEFAULT (unixepoch()) NOT NULL,
    click text,
    page text,
    referrer text,
    ip text,
    user_agent text,
    title text)

-- name: drop-stats-table
-- Removes table tracking visits
DROP TABLE IF EXISTS STATS

-- name: insert @last-id
-- Insert a data point
INSERT INTO STATS (click, page, referrer, ip, user_agent, title)
    VALUES (:click, :page, :referer, :ip, :user_agent, :title)


-- name: activity-stats
-- timeseries of activity
SELECT
    (timestamp / 600) * 600 AS time,
    count(*)
FROM
    STATS
GROUP BY
    1;

-- name: activity-places
-- timeseries of loaded places
SELECT
    (timestamp / 600) * 600 AS time,
	count(page) FILTER (WHERE page LIKE 'http://localhost:4252%') AS stats,
	count(page) FILTER (WHERE page LIKE 'http://localhost/%') AS stats_proxy,
	count(page) FILTER (WHERE page LIKE 'http://localhost:1313%') AS blog
FROM
    STATS
GROUP BY
    1
