import * as uint32 from 'uint32' ; export const SQLeetEnginePrimaryKeyName = '`key`' ; export const RESERVED_COLUMN = '__single_column_value' ; export enum SQLiteType { BOOLEAN = 'boolean' , DATETIME = 'datetime' , INTEGER = 'integer' , JSON = 'json' , JSON_OR_TEXT = 'json_or_text' , REAL = 'real' , TEXT = 'text' } export type SQLiteTableDefinition < T extends string | number | symbol > = Record < T , SQLiteType > ; export type SQLiteDatabaseDefinition < T extends string | number | symbol > = Record < T , SQLiteTableDefinition < T > > ; export type SQLiteTableSingleColumnDefinition < T extends string | number | symbol > = Record < T , SQLiteType > ; export type SQLiteProvidedSchema < T extends string | number | symbol > = Record < T , SQLiteType | SQLiteTableDefinition < T > > ; export const escape = ( value , delimiter = '`' ) => { return `${ delimiter }${ value . replace ( new RegExp ( delimiter , 'g' ) , `\\${ delimiter }` ) }${ delimiter }` ; } ; export function createTableIfNotExists < T extends string | number | symbol > ( tableName , columns ) { const escapedColumns = Object . entries ( columns ) . map ( ( [ key , type ] ) => `${ escape ( key ) } ${ type }` ) ; const statements = [ '`key` varchar(255) PRIMARY KEY' , ... escapedColumns ] ; return `CREATE TABLE IF NOT EXISTS ${ escape ( tableName ) } (${ statements . join ( ',' ) });` ; } export function getFormattedColumnsFromTableName ( tableNameColumns , withKey = false ) { const prefix = withKey ? `${ SQLeetEnginePrimaryKeyName },` : '' ; const escapedTableNameColumns = Object . keys ( tableNameColumns ) . map ( column => escape ( column ) ) . join ( ',' ) ; return `${ prefix }${ escapedTableNameColumns }` ; } export function getFormattedColumnsFromColumns ( tableNameColumns , withKey = false ) { const prefix = withKey ? `${ SQLeetEnginePrimaryKeyName },` : '' ; const escapedTableNameColumns = Object . values ( tableNameColumns ) . map ( column => escape ( column ) ) . join ( ',' ) ; return `${ prefix }${ escapedTableNameColumns }` ; } export function getProtectedColumnReferences ( columns ) { return Object . keys ( columns ) . map ( reference => `${ escape ( columns [ reference ] ) }=${ reference }` ) . join ( ',' ) ; } export function hashColumnName ( column ) { let hash = uint32 . toUint32 ( 0 ) ; const key = column . toLowerCase ( ) ; for ( let index = 0 ; index < key . length ; index ++ ) { hash = uint32 . addMod32 ( hash , uint32 . toUint32 ( key . charCodeAt ( index ) ) ) ; hash = uint32 . addMod32 ( hash , uint32 . shiftLeft ( hash , 10 ) ) ; hash = uint32 . xor ( hash , uint32 . shiftRight ( hash , 6 ) ) ; } hash = uint32 . addMod32 ( hash , uint32 . shiftLeft ( hash , 3 ) ) ; hash = uint32 . xor ( hash , uint32 . shiftRight ( hash , 11 ) ) ; hash = uint32 . addMod32 ( hash , uint32 . shiftLeft ( hash , 15 ) ) ; return hash ; } export function isSingleColumnTable ( table ) { return typeof table [ RESERVED_COLUMN ] === 'string' ; }