Skip to content

Instantly share code, notes, and snippets.

@JupyterJones
Created December 8, 2024 20:08
Show Gist options
  • Save JupyterJones/b1d84731436b68ae855f127dde4acc82 to your computer and use it in GitHub Desktop.
Save JupyterJones/b1d84731436b68ae855f127dde4acc82 to your computer and use it in GitHub Desktop.
This application, called "NOTE," is a lightweight command-line notes manager built using Python and SQLite.
#!/usr/bin/python3
import sys
import sqlite3
DATABASE = "notes.db"
conn = sqlite3.connect(DATABASE)
from datetime import datetime
conn.text_factory = str
c = conn.cursor()
if len(sys.argv) < 3:
print ("\n******* NOTE - Notes Editor ******")
print ("Not enough options were passed.")
print ("NOTE requires 2 arguments. "\
"the first -H , -R , -I , -D or -S .\n"\
"The second can be a period.")
print ("If printing the database -T also add"\
" a filename of your choice ( no quotes required ):")
print (" Example: NOTE -T Data2Text.txt")
print ("If wanting to read all entries use -R . "\
"(use the period)")
print ("even use the period with help. -H . "\
" must be entered.")
print ("*************************************\n")
sys.exit()
mod = sys.argv[1]
def create(DATABASE):
conn = sqlite3.connect(DATABASE)
conn.text_factory = str
c = conn.cursor()
c.execute("CREATE VIRTUAL TABLE PROJECT using FTS4 (input)")
conn.commit()
text = "Database Created"
return text
def insert(data,conn=conn, c=c):
datef = datetime.now().strftime("%A %D %H:%M:%S")
data = data+"\n"+datef
c.execute("INSERT into PROJECT values (?)", (data,))
for row in c.execute("SELECT ROWID,* FROM \
PROJECT ORDER BY ROWID DESC LIMIT 1"):
print ("\nPOST VERIFIED:\n",row[0],row[1])
conn.commit()
conn.close()
return data
def search(data,conn=conn, c=c):
#for row in c.execute("SELECT ROWID,* FROM \
#PROJECT WHERE input MATCH ?",(data,)):
# print ("\nINFO Found Here:",row[0],row[1])
for row in c.execute("SELECT ROWID,* FROM PROJECT"):
if data in row[1]:
print ("\nINFO Found Here:\n",row[0],row[1])
#conn.commit()
#conn.close()
def delete(rowid,conn=conn, c=c):
c.execute("DELETE FROM PROJECT WHERE rowid = ?", (rowid,))
conn.commit()
conn.close()
text = "ROWID "+rowid+" Deleted"
return text
def main(DATABASE):
conn = sqlite3.connect(DATABASE)
conn.text_factory = str
c = conn.cursor()
for row in c.execute("SELECT rowid, * FROM PROJECT"):
print (row[0],": ",row[1])
def prtmain(filename,DATABASE):
fn = open(filename, "w")
conn = sqlite3.connect(DATABASE)
conn.text_factory = str
c = conn.cursor()
for row in c.execute("SELECT rowid, * FROM PROJECT"):
TEXT = "id:"+str(row[0])+"\n"+str(row[1])
TEXT = str(TEXT)
TEXT = TEXT.replace('\\n','\n')
TEXT = "".join(TEXT)
fn.write(TEXT+'\n----\n')
def HELP():
TXT = """
USE: NOTE argv[1] argv[2]
argv[1] sets the mod:
-I insert / -D delete / -R read / -H help
examples:
Notice the entry is in parenthese.
-I to insert "STUFF to be inserted"
NOTE -I "STUFF to be inserted"
-D to delete where rowid is 3
NOTE -D 3
Notice the period after -R .
-R . read all
To search for the term "current project"
NOTE -S 3
-S "current project"
NOTE -R .
-H help on options
NOTE -H .
"""
print (TXT)
if mod == "-H" or mod == "h":
HELP()
if mod == "-R" or mod == "-r":
main()
if mod == "-I" or mod == "-i":
data = sys.argv[2]
insert(data)
if mod == "-D" or mod == "-d":
rowid = sys.argv[2]
delete(rowid)
if mod == "-S" or mod == "-s":
data = sys.argv[2]
search(data)
if mod == "-T":
filename = sys.argv[2]
prtmain(filename)
if mod == "-C" or mod == "-c":
create()
print (create)
else:
print ("_________________\n")
print (sys.argv[2],"Command Completed")
'''
This application, called "NOTE," is a lightweight command-line notes manager built using Python and SQLite. It is designed to perform various operations on a database of notes, including creating, reading, inserting, searching, deleting, and exporting entries. The application uses SQLite's FTS4 (Full-Text Search) virtual table functionality to handle and query textual data efficiently. Let's break down how the application works.
When the program is executed, it expects two arguments from the command line. The first argument specifies the mode of operation, such as creating a database, inserting a note, deleting a note, or searching the database. The second argument is context-dependent, typically a note, row identifier, or filename, depending on the mode selected. If the required arguments are not provided, the application displays a help message explaining the available options and their usage.
The program starts by establishing a connection to an SQLite database called "notes.db." If the database does not exist, it is created in the working directory. The connection remains open throughout the session to ensure all database operations can be performed seamlessly. The application uses a SQLite cursor to execute SQL queries.
The application defines multiple functions to handle different operations. First, the create function initializes the database by creating a virtual table named "PROJECT" using SQLite's FTS4 extension. This table is specifically designed for efficient full-text search operations. The create function can be invoked using the -C command-line argument, and it ensures that the database is ready to store notes.
The insert function adds a new note to the database. This function accepts a string of text, appends a timestamp to it, and stores it in the PROJECT table. After inserting the note, it confirms the operation by displaying the note's row ID and content. The function automatically commits the transaction to save the changes to the database and closes the connection to ensure data integrity.
The search function allows users to search the database for notes containing a specific keyword or phrase. Unlike a full-text search using the MATCH operator, the current implementation iterates over all rows in the table and performs a substring search on each note. Matching notes are displayed along with their row IDs. While effective for smaller datasets, this approach could be improved for larger databases by leveraging SQLite's built-in full-text search capabilities.
The delete function removes a specific note from the database based on its row ID. It deletes the entry, commits the transaction, and closes the connection to ensure the database remains consistent. A confirmation message is displayed indicating the note has been successfully deleted.
The main function retrieves and displays all notes stored in the database. Each note is shown along with its corresponding row ID, allowing users to identify and reference specific entries for further actions like deletion or updating. Similarly, the prtmain function exports the entire database to a text file specified by the user. Each note in the exported file includes its row ID, content, and a separator for clarity. This function is particularly useful for creating backups or sharing notes in a readable format.
The HELP function provides detailed instructions on how to use the application. It describes each command-line argument and provides examples for common tasks like inserting, reading, deleting, and searching notes. If the user invokes the program with the -H flag or enters invalid input, this function is displayed to guide them.
The application's control flow is managed through a series of conditional checks based on the mode specified by the first command-line argument. Depending on the mode, the corresponding function is called with the appropriate arguments. For example, the -I flag triggers the insert function to add a new note, while the -R flag invokes the main function to display all notes.
Finally, the program outputs a confirmation message once the requested operation is completed, ensuring the user is aware of the success or failure of their action. By combining SQLite's flexibility with Python's ease of use, this application provides a simple yet powerful tool for managing textual data directly from the command line.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment