📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
// This script initialises the Swetrix selfhosted edition database and tables if they're absent
const { queriesRunner, dbName } = require('./setup')
const { initialiseDatabase } = require('./initialise_database')
const CLICKHOUSE_INIT_QUERIES = [
`CREATE TABLE IF NOT EXISTS ${dbName}.api_key (
id String, userId String, name String, keyHash String,
encryptedKey String, keyPreview String, scopes String, projectIds String,
allProjects UInt8 DEFAULT 0, unrestricted UInt8 DEFAULT 0,
created Nullable(String), rotated Nullable(String)
) ENGINE = MergeTree() ORDER BY (userId, id)`,
`CREATE TABLE IF NOT EXISTS ${dbName}.session_replay_chunks
(
pid FixedString(12),
psid UInt64,
replayId String CODEC(ZSTD(3)),
chunkIndex UInt32,
objectKey String CODEC(ZSTD(3)),
privacyMode LowCardinality(String),
eventCount UInt32,
uncompressedBytes UInt32,
compressedBytes UInt32,
firstEventTimestamp Nullable(UInt64),
lastEventTimestamp Nullable(UInt64),
created DateTime('UTC') CODEC(Delta(4), LZ4),
expiresAt DateTime('UTC') CODEC(Delta(4), LZ4)
)
ENGINE = ReplacingMergeTree(created)
PARTITION BY toYYYYMM(created)
ORDER BY (pid, psid, replayId, chunkIndex);`,
`CREATE TABLE IF NOT EXISTS ${dbName}.user
(
id FixedString(36),
email String CODEC(ZSTD(3)),
password String CODEC(ZSTD(3)),
timezone String CODEC(ZSTD(3)),
timeFormat String CODEC(ZSTD(3)),
showLiveVisitorsInTitle Int8,
onboardingStep String CODEC(ZSTD(3)),
hasCompletedOnboarding Int8,
apiKey Nullable(String) CODEC(ZSTD(3)),
twoFactorAuthenticationSecret Nullable(String) CODEC(ZSTD(3)),
twoFactorRecoveryCode Nullable(String) CODEC(ZSTD(3)),
isTwoFactorAuthenticationEnabled Int8 DEFAULT 0
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.project
(
id FixedString(12),
name String CODEC(ZSTD(3)),
origins Nullable(String) CODEC(ZSTD(3)),
ipBlacklist Nullable(String) CODEC(ZSTD(3)),
ipWhitelist Nullable(String) CODEC(ZSTD(3)),
countryBlacklist Nullable(String) CODEC(ZSTD(3)),
sessionReplayRetentionDays UInt16 DEFAULT 30,
active Int8,
public Int8,
isPasswordProtected Int8,
botsProtectionLevel String DEFAULT 'basic' CODEC(ZSTD(3)),
passwordHash Nullable(String) CODEC(ZSTD(3)),
adminId Nullable(String) CODEC(ZSTD(3)),
websiteUrl Nullable(String) CODEC(ZSTD(3)),
isCaptchaProject Int8 DEFAULT 0,
captchaSecretKey Nullable(String) CODEC(ZSTD(3)),
captchaDifficulty UInt8 DEFAULT 4,
captchaDifficultyMode String DEFAULT 'manual' CODEC(ZSTD(3)),
gscPropertyUri Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),
gscAccessTokenEnc Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),
gscRefreshTokenEnc Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),
gscTokenExpiry Nullable(Int64) DEFAULT NULL,
gscScope Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),
gscAccountEmail Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),
brandKeywords Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),
created DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created)
ORDER BY (created);`,
`CREATE TABLE IF NOT EXISTS ${dbName}.pinned_project
(
id String,
visitorId String,
projectId FixedString(12),
created DateTime('UTC')
)
ENGINE = ReplacingMergeTree(created)
ORDER BY (visitorId, projectId)
PARTITION BY toYYYYMM(created);`,
`CREATE TABLE IF NOT EXISTS ${dbName}.goal
(
id FixedString(36),
name String,
type Enum8('pageview' = 1, 'custom_event' = 2),
matchType Enum8('exact' = 1, 'contains' = 2, 'regex' = 3) DEFAULT 'exact',
value Nullable(String),
metadataFilters Nullable(String),
conditions Nullable(String),
active Int8 DEFAULT 1,
projectId FixedString(12),
created DateTime
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.feature_flag
(
id String,
key String,
description Nullable(String),
flagType Enum8('boolean' = 1, 'rollout' = 2) DEFAULT 'boolean',
rolloutPercentage UInt8 DEFAULT 100,
targetingRules Nullable(String),
enabled Int8 DEFAULT 1,
experimentId Nullable(String),
scheduledChange Nullable(String),
killSwitchActive Int8 DEFAULT 0,
killSwitchValue Int8 DEFAULT 0,
killedAt Nullable(DateTime('UTC')),
targetingUpdatedAt Nullable(DateTime('UTC')),
projectId FixedString(12),
created DateTime('UTC'),
updated DateTime('UTC') DEFAULT created
)
ENGINE = ReplacingMergeTree(created)
ORDER BY (projectId, id)
PARTITION BY toYYYYMM(created);`,
`CREATE TABLE IF NOT EXISTS ${dbName}.experiment
(
id String,
name String,
description Nullable(String),
hypothesis Nullable(String),
status Enum8('draft' = 1, 'running' = 2, 'paused' = 3, 'completed' = 4) DEFAULT 'draft',
exposureTrigger Enum8('feature_flag' = 1, 'custom_event' = 2) DEFAULT 'feature_flag',
customEventName Nullable(String),
multipleVariantHandling Enum8('exclude' = 1, 'first_exposure' = 2) DEFAULT 'exclude',
filterInternalUsers Int8 DEFAULT 1,
featureFlagMode Enum8('create' = 1, 'link' = 2) DEFAULT 'create',
featureFlagKey Nullable(String),
startedAt Nullable(DateTime('UTC')),
endedAt Nullable(DateTime('UTC')),
projectId FixedString(12),
goalId Nullable(String),
featureFlagId Nullable(String),
created DateTime('UTC')
)
ENGINE = MergeTree()
ORDER BY (projectId, created, id)
PARTITION BY toYYYYMM(created);`,
`CREATE TABLE IF NOT EXISTS ${dbName}.experiment_variant
(
id String,
experimentId String,
name String,
key String,
description Nullable(String),
rolloutPercentage UInt8 DEFAULT 50,
isControl Int8 DEFAULT 0
)
ENGINE = MergeTree()
ORDER BY (experimentId, key, id);`,
`CREATE TABLE IF NOT EXISTS ${dbName}.feature_flag_evaluations
(
pid FixedString(12),
flagId String,
flagKey String,
result UInt8,
profileId String,
created DateTime('UTC')
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created)
ORDER BY (pid, flagId, created)
TTL created + INTERVAL 1 YEAR;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.refresh_token
(
userId String CODEC(ZSTD(3)),
refreshToken String CODEC(ZSTD(3))
)
ENGINE = MergeTree()
ORDER BY userId;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.funnel
(
id String CODEC(ZSTD(3)),
name String CODEC(ZSTD(3)),
steps String CODEC(ZSTD(3)),
projectId FixedString(12),
created DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.project_views
(
id FixedString(36),
projectId FixedString(12),
name String CODEC(ZSTD(3)),
type String CODEC(ZSTD(3)),
filters Nullable(String) CODEC(ZSTD(3)),
createdAt DateTime CODEC(Delta(4), LZ4),
updatedAt DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.projects_views_custom_events
(
id FixedString(36),
viewId FixedString(36),
customEventName String CODEC(ZSTD(3)),
metaKey Nullable(String) CODEC(ZSTD(3)),
metaValue Nullable(String) CODEC(ZSTD(3)),
metricKey String CODEC(ZSTD(3)),
metaValueType String CODEC(ZSTD(3))
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.project_share
(
id FixedString(36),
userId FixedString(36),
projectId FixedString(12),
role String CODEC(ZSTD(3)),
confirmed Int8,
created DateTime CODEC(Delta(4), LZ4),
updated DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.annotation
(
id FixedString(36),
projectId FixedString(12),
date Date,
text String CODEC(ZSTD(3)),
created DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.salt
(
rotation String CODEC(ZSTD(3)),
salt String CODEC(ZSTD(3)),
expiresAt DateTime CODEC(Delta(4), LZ4),
created DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
PRIMARY KEY rotation;`,
`CREATE TABLE IF NOT EXISTS ${dbName}.data_import
(
id UInt8,
projectId FixedString(12),
provider LowCardinality(String),
status Enum8('pending' = 1, 'processing' = 2, 'completed' = 3, 'failed' = 4) DEFAULT 'pending',
dateFrom Nullable(Date),
dateTo Nullable(Date),
totalRows UInt32 DEFAULT 0,
importedRows UInt32 DEFAULT 0,
invalidRows UInt32 DEFAULT 0,
errorMessage Nullable(String) CODEC(ZSTD(3)),
createdAt DateTime('UTC') DEFAULT now(),
finishedAt Nullable(DateTime('UTC')),
version UInt32 DEFAULT 1
)
ENGINE = ReplacingMergeTree(version)
ORDER BY (projectId, id);`,
]
const initialiseSelfhosted = async () => {
try {
await initialiseDatabase()
await queriesRunner(CLICKHOUSE_INIT_QUERIES)
} catch (reason) {
console.error(
`[ERROR] Error occured whilst initialising the database: ${reason}`,
)
}
}
initialiseSelfhosted()