Sounds a lot like string manipulation to me, so there's really only one tool for the job! Behold, a database written in sed!
#n
:readdb
/---/!{
N; b readdb
}
s/\(^\n\|\n---$\)//; h
:top
n
/^get/{
G
s/^get \([[:alnum:]]*\)\n\(\1:\([[:alnum:]]*\)\n\|.\)*/\3/p
$b end; b top
}
/^keys/{
g; s/:[[:alnum:]]*//gp; $b end; b top
}
/^delete/{
x; s/\(^\|\n\)/\1@/g; x; G
:trydelete
/^delete \([[:alnum:]]*\)\n[^@]*@\1/{
s/\n\?@[[:alnum:]]*:[[:alnum:]]*//
s/@//g
}
s/@\([[:alnum:]]*:[[:alnum:]]\)/\1/
/@/b trydelete
s/^[[:print:]]*\n//g
h; s/.*/OK/p; $b end; b top
}
/^set/{
x; s/\(^\|\n\)/\1@/g; x; G
:tryset
/^set \([[:alnum:]]*\) \([[:alnum:]]*\)\n[^@]*@\1/{
s/\n\?@[[:alnum:]]*:[[:alnum:]]*//
s/@//g
}
s/@\([[:alnum:]]*:[[:alnum:]]\)/\1/
/@/b tryset
s/^set \([[:alnum:]]*\) \([[:alnum:]]*\)/\1:\2/
h; s/.*/OK/p; $b end; b top
}
:end
x; s/\n\?$/\n---/; w out.txt
A database is a text file in the following format:
key1:value1
key2:value2
key3:value3
---
To run this beautiful program, use sed -f script.sed db.txt commands.txt, or pipe your command(s) in through stdin. The resultant database is written to out.txt.
Pros:
Harness the full power of sed!
Built-in backups generated on each and every command, just throw away the output file if you run the wrong one!
Haskell, because why not. Database is stored in a single csv file, called database.csv. There is no usage summary available - only the responses OK, ERROR, or the requested data item(s) are printed. Extra parameters are ignored. Keys are always printed out in sorted order.
module Main ( main ) where
import qualified Data.ByteString.Lazy as BL
import Control.Monad
import Data.Csv
import qualified Data.List as List
import qualified Data.Vector as Vector
import System.Directory
import System.Environment
import System.Exit
data Entry = Entry { key :: !String, value :: !String }
deriving (Show)
instance FromRecord Entry where
parseRecord v
| List.length v == 2 = Entry <$> v .! 0 <*> v .! 1
| otherwise = mzero
instance ToRecord Entry where
toRecord (Entry k v) = record [ toField k, toField v ]
dataFileName = "database.csv"
main = do
args <- getArgs
if List.length args < 1
then die "ERROR"
else let command = List.head args
params = List.tail args
in case command of
"set" -> handleSet params
"get" -> handleGet params
"keys" -> handleKeys
"delete" -> handleDelete params
_ -> die "ERROR"
readDB = do
databaseExists <- doesFileExist dataFileName
if databaseExists
then do
csvData <- BL.readFile dataFileName
case decode NoHeader csvData :: Either String (Vector.Vector Entry) of
Left err -> die "ERROR"
Right entries -> return $ Vector.toList entries
else return []
writeDB entries =
BL.writeFile dataFileName (encode entries)
handleSet params =
if List.length params < 2
then die "ERROR"
else let k = List.head params
v = List.head (List.tail params)
in do
entries <- readDB
if List.elem k (List.map key entries)
then let entriesMinusOldItem =
List.filter (\x -> key x /= k) entries
entries' = (Entry k v):entriesMinusOldItem
in writeDB entries' >> putStrLn "OK"
else let entries' = (Entry k v):entries
in writeDB entries' >> putStrLn "OK"
handleGet params =
if List.length params < 1
then die "ERROR"
else let k = List.head params
in do
entries <- readDB
case (List.find (\x -> (key x) == k) entries) of
Nothing -> die "ERROR"
Just (Entry k v) -> putStrLn v
handleKeys = do
entries <- readDB
mapM_ putStrLn (List.sort $ List.map key entries)
handleDelete params =
if List.length params < 1
then die "ERROR"
else let k = List.head params
in do
entries <- readDB
if List.elem k (List.map key entries)
then let entriesMinusOldItem =
List.filter (\x -> key x /= k) entries
in writeDB entriesMinusOldItem >> putStrLn "OK"
else die "ERROR"
Some examples:
$ ./database keys
$ ./database get
ERROR
$ ./database get one
ERROR
$ ./database set one uno
OK
$ ./database set two dos
OK
$ ./database set three tres
OK
$ ./database get two
dos
$ ./database keys
one
three
two
$ ./database delete two
OK
$ ./database keys
one
three
$ ./database get two
ERROR
$ ./database get one
uno
C. Tested on Linux x86_64 with GCC, appears to work with MinGW, not sure about other platforms and compilers.
set reads from stdin without value argument for convenient storage of binary data. Error messages are written to stderr. No memory is freed, no files are closed. Key-value pairs are stored in a revolutionary database format optimized for linear search.
Here's my entry, i tried to replicate my code from when i just learned python. I was going to mess up the indention scopes, but i couldn't bring myself to force someone to read that. Naturally, this has the following bugs:
Passing too few arguments will error
No shebang is a problem in some environments
Sequential open calls to the same file is bad
You can store multiple values under the same key (This is a feature)
Calling bbcc37 get or bbcc37 delete before creating data.sql will error
bbcc37 get key prints in the ugly format key=value
The data.sql file will have random extra newlines
keys may not contain the = character
And it has the following advantages:
The data file can be opened in a text editor and it's human readable
Will print useful tracebacks to any errors that occur
The program checks for get requests first, so those will be most efficient by several microseconds
Only uses default python libraries, no need to pip install anything
import sys
ENTER_CHARACTER = """
"""
if sys.argv[1] == "get":
f = open("data.sql", "r+")
for line in f.readlines():
# whats string.split
key = ""
for character in line:
if character == "=":
break
key = key + character
if key == sys.argv[2]:
print(line)
if sys.argv[1] == "set":
f = open("data.sql", "a+")
f.write(sys.argv[2])
f.write("=")
f.write(sys.argv[3])
f.write(ENTER_CHARACTER)
if sys.argv[1] == "keys":
f = open("data.sql", "r+")
for line in f.readlines():
key = ""
for character in line:
if character == "=":
break
key = key + character
print(key)
if sys.argv[1] == "delete":
f = open("data.sql", "r")
all_lines = f.readlines()
f = open("data.sql", "w+")
f.truncate()
for line in all_lines:
key = ""
for character in line:
if character == "=":
break
key = key + character
if key == sys.argv[2]:
# don't write this line back into the database
print("deleted")
else:
f.write(line)
f.write(ENTER_CHARACTER)```
It uses your web browser, so its universal and mobile and will never have compatibility issues
It uses javascript and the window global scope, which are indisputably best practices
It uses localStorage without checking if it's supported and has no input validation, which of course would waste cpu cycles
It accepts commands in url form, from the console or by modifying the local storage directly, which provides flexibility, never mind that a single typo will break everything.
25
u/sarlok May 25 '20
That sounds an awful lot like a filesystem, so why don't we just use that? Behold, bbcc37.cmd:
Features:
directorydatabase automatically called bbcc37!Usage for Windows (from cmd command prompt):
Usage for Linux (from bash shell):
8
u/mathishard821 May 31 '20
Sounds a lot like string manipulation to me, so there's really only one tool for the job! Behold, a database written in sed!
A database is a text file in the following format:
To run this beautiful program, use
sed -f script.sed db.txt commands.txt, or pipe your command(s) in through stdin. The resultant database is written toout.txt.Pros:
6
u/[deleted] May 26 '20 edited May 26 '20
Haskell, because why not. Database is stored in a single csv file, called database.csv. There is no usage summary available - only the responses OK, ERROR, or the requested data item(s) are printed. Extra parameters are ignored. Keys are always printed out in sorted order.
Some examples:
3
u/bytesomething May 29 '20
C. Tested on Linux x86_64 with GCC, appears to work with MinGW, not sure about other platforms and compilers.
setreads from stdin without value argument for convenient storage of binary data. Error messages are written to stderr. No memory is freed, no files are closed. Key-value pairs are stored in a revolutionary database format optimized for linear search.https://pastebin.com/yX9Uhh5X
2
u/gaberocksall May 25 '20 edited May 25 '20
Here's my entry, i tried to replicate my code from when i just learned python. I was going to mess up the indention scopes, but i couldn't bring myself to force someone to read that. Naturally, this has the following bugs:
opencalls to the same file is badbbcc37 getorbbcc37 deletebefore creatingdata.sqlwill errorbbcc37 get keyprints in the ugly formatkey=valuedata.sqlfile will have random extra newlines=characterAnd it has the following advantages:
getrequests first, so those will be most efficient by several microsecondspip installanything
3
u/--var May 25 '20
After about 30 minutes I've concocted this little gem:
WHY YOUR COMPANY NEEDS THIS:
It uses your web browser, so its universal and mobile and will never have compatibility issues
It uses javascript and the window global scope, which are indisputably best practices
It uses localStorage without checking if it's supported and has no input validation, which of course would waste cpu cycles
It accepts commands in url form, from the console or by modifying the local storage directly, which provides flexibility, never mind that a single typo will break everything.
USE EXAMPLES:
in the url
in the console
0
u/[deleted] May 25 '20
[deleted] — view deleted comment
0
u/[deleted] May 25 '20
[deleted] — view deleted comment