Skip to content
This repository has been archived by the owner on Nov 19, 2022. It is now read-only.

Commit

Permalink
Execute schema on start
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelmota committed Aug 12, 2019
1 parent ed01792 commit b7631df
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 22 deletions.
111 changes: 111 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
Executable File 110 lines (95 sloc) 1.3 KB

//this will affect all the git repos
git config --global core.excludesfile ~/.gitignore


//update files since .ignore won't if already tracked
git rm --cached <file>

# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so

# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip

# Logs and databases #
######################
*.log
*.sql
*.sqlite

# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
# Icon?
ehthumbs.db
Thumbs.db
.cache
.project
.settings
.tmproj
*.esproj
nbproject

# Numerous always-ignore extensions #
#####################################
*.diff
*.err
*.orig
*.rej
*.swn
*.swo
*.swp
*.vi
*~
*.sass-cache
*.grunt
*.tmp

# Dreamweaver added files #
###########################
_notes
dwsync.xml

# Komodo #
###########################
*.komodoproject
.komodotools

# Node #
#####################
node_modules

# Bower #
#####################
bower_components

# Vim files to ignore #
#######################
.VimballRecord
.netrwhist

# Folders to ignore #
#####################
.hg
.svn
.CVS
intermediate
publish
.idea
.graphics
_test
_archive
uploads
tmp

# Files to ignore #
###################
package-lock.json
data.txt
todo.txt
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,6 @@ rollback:

migrate/new:
(cd migration && rake db:new_migration name=$(NAME))

schema:
sqlite3 data/sqlite3.db .schema > schema.sql
2 changes: 1 addition & 1 deletion cmd/streamhut/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ For more info, visit: https://github.com/streamhut/streamhut`,

serverCmd.Flags().UintVarP(&httpPort, "port", "p", 8080, "HTTP Port")
serverCmd.Flags().UintVarP(&tcpPort, "tcp-port", "t", 1337, "TCP Port")
serverCmd.Flags().StringVarP(&dbPath, "db-path", "", "./data/sqlite3.db", "Sqlite3 database path")
serverCmd.Flags().StringVarP(&dbPath, "db-path", "", sqlite3db.DefaultDBPath, "Sqlite3 database path")
serverCmd.Flags().StringVarP(&dbType, "db-type", "", "sqlite3", "Database type: Options are \"sqlite\"")
serverCmd.Flags().StringVarP(&shareBaseURL, "share-base-url", "", os.Getenv("HOST_URL"), "Share base URL. Example: \"https://stream.ht/\"")
serverCmd.Flags().StringVarP(&webTarURL, "web-tar-url", "", httpserver.DefaultWebTarURL, "Web app tarball url to download")
Expand Down
Binary file removed data/sqlite3.db
Binary file not shown.
3 changes: 0 additions & 3 deletions package-lock.json

This file was deleted.

87 changes: 70 additions & 17 deletions pkg/db/sqlite3db/sqlite3.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,20 @@ package sqlite3db

import (
"database/sql"
"fmt"
"log"
"os"
"strings"
"sync"
"time"

"github.com/streamhut/streamhut/pkg/util"
"github.com/streamhut/streamhut/types"
)

// DefaultDBPath is the default path for the sqlite3 database
var DefaultDBPath = "~/.streamhut/db/sqlite3.db"

// Config ...
type Config struct {
DBPath string
Expand All @@ -21,29 +28,57 @@ type DB struct {

// NewDB ...
func NewDB(config *Config) *DB {
db, err := sql.Open("sqlite3", config.DBPath+"?cache=shared&mode=rwc&_busy_timeout=5000")
dbPath := util.NormalizePath(config.DBPath)

if _, err := os.Stat(dbPath); os.IsNotExist(err) {
dbDirPath := util.FilePath(dbPath)
if _, err := os.Stat(dbDirPath); os.IsNotExist(err) {
if err := os.MkdirAll(dbDirPath, 0700); err != nil {
log.Fatal(err)
}
}

f, err := os.Create(dbPath)
if err != nil {
log.Fatal(err)
}

f.Close()
}

db, err := sql.Open("sqlite3", fmt.Sprintf("%s?cache=shared&mode=rwc&_busy_timeout=5000", dbPath))
if err != nil {
log.Fatal(err)
}
return &DB{
db: db,

svc := &DB{db}
for _, line := range svc.schema() {
if len(line) < 3 {
continue
}

tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
stmt, err := tx.Prepare(line)
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec()
if err != nil {
log.Fatal(err)
}
if err := tx.Commit(); err != nil {
if err := tx.Rollback(); err != nil {
log.Fatal(err)
}
}
}
}

/*
if (!fs.existsSync(dbPath)) {
const schemaPath = path.resolve(__dirname, '..', 'db/schema.sql')
db.serialize(function() {
const lines = fs.readFileSync(schemaPath, 'utf8').split('\n').filter(x => x)
for (var i = 0; i < lines.length; i++) {
if (lines[i].indexOf('sqlite_sequence') > -1) {
continue
}
db.run(lines[i]);
}
})
return svc
}
*/

// Close ...
func (d *DB) Close() error {
Expand Down Expand Up @@ -171,3 +206,21 @@ func (d *DB) InsertStreamMessage(msg *types.StreamMessage) {
}
}
}

func (d *DB) schema() []string {
schema := `
CREATE TABLE IF NOT EXISTS "schema_migrations" ("version" varchar NOT NULL PRIMARY KEY);
CREATE TABLE IF NOT EXISTS "ar_internal_metadata" ("key" varchar NOT NULL PRIMARY KEY, "value" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
CREATE TABLE IF NOT EXISTS "stream_logs" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "stream_handle" blob NOT NULL, "data" blob NOT NULL, "created_at" datetime DEFAULT CURRENT_TIMESTAMP NOT NULL);
CREATE INDEX IF NOT EXISTS "index_stream_logs_on_stream_handle" ON "stream_logs" ("stream_handle");
CREATE INDEX IF NOT EXISTS "index_stream_logs_on_data" ON "stream_logs" ("data");
CREATE INDEX IF NOT EXISTS "index_stream_logs_on_created_at" ON "stream_logs" ("created_at");
CREATE TABLE IF NOT EXISTS "stream_messages" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "stream_handle" blob NOT NULL, "message" blob NOT NULL, "mime" blob NOT NULL, "created_at" datetime DEFAULT CURRENT_TIMESTAMP NOT NULL);
CREATE INDEX IF NOT EXISTS "index_stream_messages_on_stream_handle" ON "stream_messages" ("stream_handle");
CREATE INDEX IF NOT EXISTS "index_stream_messages_on_mime" ON "stream_messages" ("mime");
CREATE INDEX IF NOT EXISTS "index_stream_messages_on_data" ON "stream_messages" ("data");
CREATE INDEX IF NOT EXISTS "index_stream_messages_on_created_at" ON "stream_messages" ("created_at");
`

return strings.Split(schema, "\n")
}
2 changes: 1 addition & 1 deletion pkg/httpserver/httpserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (s *Server) downloadWebBuildIfNotExists() error {
}

if _, err := os.Stat(s.staticDirPath); os.IsNotExist(err) {
if err := os.MkdirAll(s.staticDirPath, os.ModePerm); err != nil {
if err := os.MkdirAll(s.staticDirPath, 0700); err != nil {
return err
}
}
Expand Down
6 changes: 6 additions & 0 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,9 @@ func NormalizePath(path string) string {

return path
}

// FilePath returns the path for the file
func FilePath(path string) string {
parts := strings.Split(path, string(filepath.Separator))
return strings.Join(parts[:len(parts)-1], string(filepath.Separator))
}

0 comments on commit b7631df

Please sign in to comment.