Home Download Docs Code Community
     1	/*
     2	Copyright 2012 The Perkeep Authors.
     3	
     4	Licensed under the Apache License, Version 2.0 (the "License");
     5	you may not use this file except in compliance with the License.
     6	You may obtain a copy of the License at
     7	
     8	     http://www.apache.org/licenses/LICENSE-2.0
     9	
    10	Unless required by applicable law or agreed to in writing, software
    11	distributed under the License is distributed on an "AS IS" BASIS,
    12	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13	See the License for the specific language governing permissions and
    14	limitations under the License.
    15	*/
    16	
    17	package sqlite
    18	
    19	import (
    20		"database/sql"
    21		"fmt"
    22		"log"
    23		"strconv"
    24	
    25		"perkeep.org/pkg/sorted"
    26	)
    27	
    28	const requiredSchemaVersion = 1
    29	
    30	func SchemaVersion() int {
    31		return requiredSchemaVersion
    32	}
    33	
    34	func SQLCreateTables() []string {
    35		// sqlite ignores n in VARCHAR(n), but setting it as such for consistency with
    36		// other sqls.
    37		return []string{
    38			`CREATE TABLE rows (
    39	 k VARCHAR(` + strconv.Itoa(sorted.MaxKeySize) + `) NOT NULL PRIMARY KEY,
    40	 v VARCHAR(` + strconv.Itoa(sorted.MaxValueSize) + `))`,
    41	
    42			`CREATE TABLE meta (
    43	 metakey VARCHAR(255) NOT NULL PRIMARY KEY,
    44	 value VARCHAR(255) NOT NULL)`,
    45		}
    46	}
    47	
    48	// InitDB creates a new sqlite database based on the file at path.
    49	func InitDB(path string) error {
    50		db, err := sql.Open("sqlite", path)
    51		if err != nil {
    52			return err
    53		}
    54		defer db.Close()
    55		for _, tableSQL := range SQLCreateTables() {
    56			if _, err := db.Exec(tableSQL); err != nil {
    57				return err
    58			}
    59		}
    60	
    61		// Use Write Ahead Logging which improves SQLite concurrency.
    62		// Requires SQLite >= 3.7.0
    63		if _, err := db.Exec("PRAGMA journal_mode = WAL"); err != nil {
    64			return err
    65		}
    66	
    67		// Check if the WAL mode was set correctly
    68		var journalMode string
    69		if err = db.QueryRow("PRAGMA journal_mode").Scan(&journalMode); err != nil {
    70			log.Fatalf("Unable to determine sqlite3 journal_mode: %v", err)
    71		}
    72		if journalMode != "wal" {
    73			log.Fatal("SQLite Write Ahead Logging (introducted in v3.7.0) is required. See http://perkeep.org/issue/114")
    74		}
    75	
    76		_, err = db.Exec(fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, SchemaVersion()))
    77		return err
    78	}
Website layout inspired by memcached.
Content by the authors.