Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | 349x 243x 14x 25x 25x 65x 18x 105x 10x 10x 3x 3x 3x 3x 87x 39x 2x 4x 2x 27x 6x 2x 3x 2x 3x 1x 1x 1x 145x 38x 38x 38x 38x 38x 38x 8x 17x 17x 10x 10x 33112x 112x 33000x 1x 32999x 4x 32997x 11766x 21231x 3x 2x 1x 1x 276x 44399x | /**
* SQLite Database Adapter
* Implements SQLite-specific SQL generation for time dimensions, string matching, and type casting
* Supports local SQLite with better-sqlite3 driver
*/
import { sql, type SQL, type AnyColumn } from 'drizzle-orm'
import type { TimeGranularity } from '../types'
import { BaseDatabaseAdapter } from './base-adapter'
export class SQLiteAdapter extends BaseDatabaseAdapter {
getEngineType(): 'sqlite' {
return 'sqlite'
}
/**
* Build SQLite time dimension using date/datetime functions with modifiers
* For integer timestamp columns (milliseconds), first convert to datetime
* SQLite doesn't have DATE_TRUNC like PostgreSQL, so we use strftime and date modifiers
* Returns datetime strings for consistency with other databases
*/
buildTimeDimension(granularity: TimeGranularity, fieldExpr: AnyColumn | SQL): SQL {
// For SQLite with Drizzle's { mode: 'timestamp' }, timestamps are stored as Unix seconds
// The datetime() function with 'unixepoch' expects seconds, so no conversion needed
// For SQLite, we need to apply modifiers directly in the datetime conversion
// to avoid nested datetime() calls which don't work properly
switch (granularity) {
case 'year':
// Start of year: 2023-01-01 00:00:00
return sql`datetime(${fieldExpr}, 'unixepoch', 'start of year')`
case 'quarter':
// Calculate quarter start date using SQLite's date arithmetic
// First convert to datetime, then calculate quarter
const dateForQuarter = sql`datetime(${fieldExpr}, 'unixepoch')`
return sql`datetime(${dateForQuarter}, 'start of year',
'+' || (((CAST(strftime('%m', ${dateForQuarter}) AS INTEGER) - 1) / 3) * 3) || ' months')`
case 'month':
// Start of month: 2023-05-01 00:00:00
return sql`datetime(${fieldExpr}, 'unixepoch', 'start of month')`
case 'week':
// Start of week (Monday): Use SQLite's weekday modifier
// weekday 1 = Monday, so go to Monday then back 6 days to get start of week
return sql`date(datetime(${fieldExpr}, 'unixepoch'), 'weekday 1', '-6 days')`
case 'day':
// Start of day: 2023-05-15 00:00:00
return sql`datetime(${fieldExpr}, 'unixepoch', 'start of day')`
case 'hour':
// Truncate to hour: 2023-05-15 14:00:00
const dateForHour = sql`datetime(${fieldExpr}, 'unixepoch')`
return sql`datetime(strftime('%Y-%m-%d %H:00:00', ${dateForHour}))`
case 'minute':
// Truncate to minute: 2023-05-15 14:30:00
const dateForMinute = sql`datetime(${fieldExpr}, 'unixepoch')`
return sql`datetime(strftime('%Y-%m-%d %H:%M:00', ${dateForMinute}))`
case 'second':
// Already at second precision: 2023-05-15 14:30:25
const dateForSecond = sql`datetime(${fieldExpr}, 'unixepoch')`
return sql`datetime(strftime('%Y-%m-%d %H:%M:%S', ${dateForSecond}))`
default:
// Fallback to converting the timestamp to datetime without truncation
return sql`datetime(${fieldExpr}, 'unixepoch')`
}
}
/**
* Build SQLite string matching conditions using LOWER() + LIKE for case-insensitive matching
* SQLite LIKE is case-insensitive by default, but LOWER() ensures consistency
*/
buildStringCondition(fieldExpr: AnyColumn | SQL, operator: 'contains' | 'notContains' | 'startsWith' | 'endsWith' | 'like' | 'notLike' | 'ilike' | 'regex' | 'notRegex', value: string): SQL {
switch (operator) {
case 'contains':
return sql`LOWER(${fieldExpr}) LIKE ${`%${value.toLowerCase()}%`}`
case 'notContains':
return sql`LOWER(${fieldExpr}) NOT LIKE ${`%${value.toLowerCase()}%`}`
case 'startsWith':
return sql`LOWER(${fieldExpr}) LIKE ${`${value.toLowerCase()}%`}`
case 'endsWith':
return sql`LOWER(${fieldExpr}) LIKE ${`%${value.toLowerCase()}`}`
case 'like':
return sql`${fieldExpr} LIKE ${value}`
case 'notLike':
return sql`${fieldExpr} NOT LIKE ${value}`
case 'ilike':
// SQLite doesn't have ILIKE, use LOWER() + LIKE for case-insensitive
return sql`LOWER(${fieldExpr}) LIKE ${value.toLowerCase()}`
case 'regex':
// SQLite regex requires loading extension, use GLOB as fallback
return sql`${fieldExpr} GLOB ${value}`
case 'notRegex':
// SQLite regex requires loading extension, use NOT GLOB as fallback
return sql`${fieldExpr} NOT GLOB ${value}`
default:
throw new Error(`Unsupported string operator: ${operator}`)
}
}
/**
* Build SQLite type casting using CAST() function
* SQLite has dynamic typing but supports CAST for consistency
*/
castToType(fieldExpr: AnyColumn | SQL, targetType: 'timestamp' | 'decimal' | 'integer'): SQL {
switch (targetType) {
case 'timestamp':
// For integer timestamp columns, convert to datetime
// Assumes millisecond Unix timestamps
return sql`datetime(${fieldExpr} / 1000, 'unixepoch')`
case 'decimal':
// Cast to REAL for decimal numbers
return sql`CAST(${fieldExpr} AS REAL)`
case 'integer':
return sql`CAST(${fieldExpr} AS INTEGER)`
default:
throw new Error(`Unsupported cast type: ${targetType}`)
}
}
/**
* Build SQLite AVG aggregation with IFNULL for NULL handling
* SQLite AVG returns NULL for empty sets, using IFNULL for consistency
*/
buildAvg(fieldExpr: AnyColumn | SQL): SQL {
return sql`IFNULL(AVG(${fieldExpr}), 0)`
}
/**
* Build SQLite CASE WHEN conditional expression
*/
buildCaseWhen(conditions: Array<{ when: SQL; then: any }>, elseValue?: any): SQL {
// Check if 'then' values are SQL objects (they have queryChunks property)
// If so, we need to treat them as SQL expressions, not bound parameters
const cases = conditions.map(c => {
// Check if it's a SQL object by checking for SQL-like properties
const isSqlObject = c.then && typeof c.then === 'object' &&
(c.then.queryChunks || c.then._ || c.then.sql);
if (isSqlObject) {
// It's a SQL expression, embed it directly without parameterization
return sql`WHEN ${c.when} THEN ${sql.raw('(') }${c.then}${sql.raw(')')}`
} else E{
// It's a regular value, parameterize it
return sql`WHEN ${c.when} THEN ${c.then}`
}
}).reduce((acc, curr) => sql`${acc} ${curr}`)
Iif (elseValue !== undefined) {
const isElseSqlObject = elseValue && typeof elseValue === 'object' &&
(elseValue.queryChunks || elseValue._ || elseValue.sql);
if (isElseSqlObject) {
return sql`CASE ${cases} ELSE ${sql.raw('(')}${elseValue}${sql.raw(')')} END`
} else {
return sql`CASE ${cases} ELSE ${elseValue} END`
}
}
return sql`CASE ${cases} END`
}
/**
* Build SQLite boolean literal
* SQLite uses 1/0 for true/false
*/
buildBooleanLiteral(value: boolean): SQL {
return value ? sql`1` : sql`0`
}
/**
* Preprocess calculated measure templates for SQLite-specific handling
*
* SQLite performs integer division by default (5/2 = 2 instead of 2.5).
* This method wraps division operands with CAST to REAL to ensure float division.
*
* Pattern matched: {measure1} / {measure2} or {measure1} / NULLIF({measure2}, 0)
* Transforms to: CAST({measure1} AS REAL) / ...
*
* @param calculatedSql - Template string with {member} references
* @returns Preprocessed template with CAST for division operations
*/
preprocessCalculatedTemplate(calculatedSql: string): string {
// Match division patterns: {anything} / {anything} or {anything} / NULLIF(...)
// We need to cast the numerator to REAL to ensure float division
// Pattern: captures the opening brace and content before division operator
const divisionPattern = /(\{[^}]+\})\s*\/\s*/g
return calculatedSql.replace(divisionPattern, (_match, numerator) => {
// Replace {measure} with CAST({measure} AS REAL)
const castNumerator = numerator.replace(/\{([^}]+)\}/, 'CAST({$1} AS REAL)')
return `${castNumerator} / `
})
}
/**
* Convert filter values to SQLite-compatible types
* SQLite doesn't support boolean types - convert boolean to integer (1/0)
* Convert Date objects to milliseconds for integer timestamp columns
*/
convertFilterValue(value: any): any {
if (typeof value === 'boolean') {
return value ? 1 : 0
}
if (value instanceof Date) {
return value.getTime()
}
if (Array.isArray(value)) {
return value.map(v => this.convertFilterValue(v))
}
// If it's already a number (likely already converted timestamp), return as-is
if (typeof value === 'number') {
return value
}
return value
}
/**
* Prepare date value for SQLite integer timestamp storage
* Convert Date objects to milliseconds (Unix timestamp * 1000)
*/
prepareDateValue(date: Date): any {
if (!(date instanceof Date)) {
// prepareDateValue called with non-Date value
// Try to handle it gracefully
if (typeof date === 'number') return date
Eif (typeof date === 'string') return new Date(date).getTime()
throw new Error(`prepareDateValue expects a Date object, got ${typeof date}`)
}
return date.getTime()
}
/**
* SQLite stores timestamps as integers (milliseconds)
*/
isTimestampInteger(): boolean {
return true
}
/**
* Convert SQLite time dimension results back to Date objects
* SQLite time dimensions return datetime strings, but clients expect Date objects
*/
convertTimeDimensionResult(value: any): any {
return value
}
} |