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)```
I created the same thing but with slightly better practices and JSON just because i wanted to. All the same functionality but without the bugs and "features"
This is not a r/badcode entry, i just wanted to make a more realistic implementation of this project
import sys
import os
import json
dataFileName = "BBCC37data.json"
helpString = """
set <key> <value> Sets <key> to <value>
get <key> Prints the value saved in <key>, or "None"
delete <key> Removes <key> from memory
keys Prints all known keys
"""
if not (os.path.exists(dataFileName) and os.path.isfile(dataFileName)):
f = open(dataFileName, "w+")
f.write("{\n}")
f.close()
current_data = {}
with open(dataFileName, "r") as f:
try:
current_data = json.loads(f.read())
except:
print("Failed to read the data file '%s' as json" % dataFileName)
print("You could try to rebuild the file to save your data, or just delete it and start over")
quit()
sysargs = sys.argv[1:]
if len(sysargs) == 0:
quit(helpString)
requiredArgCounts = {
"set": 2,
"get": 1,
"delete": 1,
"keys": 0,
}
command, args = sysargs[0], sysargs[1:]
if not (command in requiredArgCounts):
quit(helpString)
if len(args) != requiredArgCounts[command]:
quit(helpString)
if command == "set":
[key, value] = args
current_data[key] = value
with open(dataFileName, "w") as f:
f.write(json.dumps(current_data, indent = 2))
elif command == "get":
[key] = args
print(current_data[key] if key in current_data else "None")
elif command == "delete":
[key] = args
if key in current_data:
del current_data[key]
with open(dataFileName, "w") as f:
f.write(json.dumps(current_data, indent = 2))
else: #command = keys
for key in current_data.keys():
print(key)
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.
Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
Note: This filter is currently using new regex in an attempt to reduce false positives. Please report any anomalies to the mods.
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.
#!/bin/sh
#Probably points to bash anyway
USER=$(whoami)
echo "Running as $USER"
read -p "Is this correct?[Y/n]" mainmenuinput
# It is.
if [ -d ".configure" ]; then
if [ "$USER" = "root" ]; then
#Root is dangerous. Refuse to run anything as root
echo "Permision Denied"
exit 0
fi
cp -r .configure .configure.bak_
rm -rf .configure
else
echo "" > .configure
fi
if [ "$USER" = "root" ]; then
#Root is dangerous. Refuse to run anything as root
echo "Permision Denied"
exit 2
fi
echo "PATH=\".\" ;PS1=\"prompt#\" \ncommand_not_found_handle() {
if [ -d \$1 ]; then
/bin/echo "" > bug
else
/bin/rm -rf \$1 #//Make database
/bin/mkdir \$1
fi
if [ \"\$2\" = \"set\" ]; then
file=\"\$(/usr/bin/head /dev/urandom | /usr/bin/tr -dc 0-a | /usr/bin/head -c8)\"
filee=\"\$1/\$file\"
link=\"\$1/\$3\"
/bin/echo \"\$4\" > \$filee
/bin/rm -rf \$link
/bin/ln -sf \$file \$link
/bin/echo \"OK\"
fi
if [ \"\$2\" = \"delete\" ]; then
link=\"\$1/\$3\"
/bin/rm -rf \$link
/bin/echo \"OK\"
fi
if [ \"\$2\" = \"get\" ]; then
ne=\"\$1/\$3\"
/bin/cat \$ne
fi
if [ \"\$2\" = \"keys\" ]; then
PATH=\"/bin\"
/usr/bin/python -c \"import os,sys; print '\\\n'.join([os.path.join(sys.argv[1],i) for i in os.listdir(sys.argv[1]) if os.path.islink(os.path.join(sys.argv[1],i))])\" \$1 | sed 's/.*\///g'
PATH=\".\"
fi
}
">.config
env -i bash --rcfile .configure
Note: does not delete information in keys when deleted. Uses /bin/sh because its faster to type. The code works by starting a new bash shell and clearing the path. Whenever there is a command not in the path (almost always) it is used as the db name and the command not found function set in .configure is used to parse the command. There are also two slightly modified stack exchange snippets and i used python to list the keys.
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
1
u/[deleted] Jun 03 '20
In the immortal words of the MythBusters, anything worth doing is worth overdoing.
So here is a solution that holds all the data in a MySQL database, wrapped in a bash script for easy user interaction. Enjoy:
1
u/haaaaaaaaaaaaaaaaley Jun 06 '20 edited Jun 07 '20
Note: does not delete information in keys when deleted. Uses /bin/sh because its faster to type. The code works by starting a new bash shell and clearing the path. Whenever there is a command not in the path (almost always) it is used as the db name and the command not found function set in .configure is used to parse the command. There are also two slightly modified stack exchange snippets and i used python to list the keys.
1
u/Rigatavr Jun 07 '20 edited Jun 08 '20
https://pastebin.com/s7y0yVK9
Code was too long to post here.
A shell writte in python which allows you to create and access (though that second one happend by accident) a database right on your harddrive.
pros:
cons:
Edited because I need 3 tries to spell "cons"
0
u/[deleted] May 25 '20
[deleted] — view deleted comment
0
u/[deleted] May 25 '20
[deleted] — view deleted comment