Knowledge_forge / knowledge_base.json
nisaralll's picture
done
a2f5754
Raw History Blame Contribute Delete
61.9 kB
[
{
"text": "Linked lists are the new data structure we'll explore today. The study of linked lists will certainly be detailed, but first, I would like to inform you about one of the fundamental differences between linked lists and arrays. Arrays demand a contiguous memory location. Lengthening an array is not possible. We would have to copy the whole array to some bigger memory location to lengthen its size. Similarity inserting or deleting an element causes the elements to shift right and left, respectively. But linked lists are stored in a non-contiguous memory location. To add a new element, we just have to create a node somewhere in the memory and get it pointed by the previous element. And deleting an element is just as easy as that. We just have to skip pointing to that particular node. Lengthening a linked list is not a big deal. Every element in a linked list is called a node and consists of two parts, the data part, and the pointer part. The data part stores the value, while the pointer part stores the pointer pointing to the address of the next node. Both of these structures (arrays and linked lists) are linear data structures. Figure 1: Arrays vs. Linked lists Memory and the capacity of an array remain fixed, while in linked lists, we can keep adding and removing elements without any capacity constraint. Linked lists are implemented in C language using a structure. You can refer to the snippet below. Understanding the snippet below: Code Snippet 1: Implementation of a linked list These were just the basics of the linked lists. We haven\u2019t delved into details yet. There\u2019s a lot to cover in this data structure. Just sit back and enjoy. Thank you for being with me throughout. I hope you enjoyed the tutorial. If you appreciate my work, please let your friends know about this course too. Don\u2019t forget to download the notes from the link below. If you haven\u2019t checked out the whole playlist yet, move on tocodewithharry.comor my YouTube channel to access it. See you all in the next tutorial, where we\u2019ll explore more of the functionalities of linked lists. Till then, keep learning. Download Notes here",
"source": "https://www.codewithharry.com/videos/data-structures-and-algorithms-in-hindi-13/",
"type": "web",
"timestamp": "8d50ed76-993b-46ed-8854-ae806810b962"
},
{
"text": "The Ultimate No-Code AI Toolkit Introduction This README is your ultimate resource for building AI agents without coding expertise, tailored to: Fintech (e.g., fraud detection) Cybersecurity (e.g., threat monitoring) Healthcare (e.g., diagnostics) Social Media (e.g., content moderation) Social Cause (e.g., disaster relief) I've expanded the toolkit with new no-code/low-code options, reducing code-based tools to focus on accessibility. Categories include: Core ML: Predictive models, classification, anomaly detection for structured data. DL: Neural networks for images, audio, or complex patterns. NLP: Text analysis, sentiment, and conversational AI. GenAI: Content creation, simulations, and synthetic data generation. Database Management: Data storage, organization, and querying. Each tool is detailed with real-world applications, pricing, and links\u2014everything you need for a hackathon win! Core Machine Learning (ML) Tools Tools for predictive modeling, classification, regression, and anomaly detection with minimal coding. 1. Akkio (No-Code) Description: Akkio is a no-code platform that simplifies predictive analytics by letting you upload structured data (e.g., CSVs), train models, and deploy them instantly. It's beginner-friendly, fast, and perfect for tabular data tasks like fraud detection or risk scoring. Usage Across Domains: Fintech: Detect suspicious transactions by training on columns like amount, timestamp, and user ID, outputting \"safe\" or \"fraud\" labels. Cybersecurity: Flag unusual network traffic from logs (e.g., IP, bytes transferred) to spot potential intrusions. Healthcare: Predict patient readmission risks using data like age, vitals, and past visits. Social Media: Classify user behavior (e.g., clicks, shares) to predict viral content. Social Cause: Forecast crowdfunding success based on donation amounts and campaign duration. Free Status: Free tier (500 predictions/month); paid plans start at $49/month for unlimited predictions and API access. Website: akkio.com Integration: REST API for real-time predictions, CSV exports, pairs with Bubble or Google Sheets for dashboards. 2. Google AutoML (No-Code/Low-Code) Description: Google AutoML, part of Google Cloud, offers no-code/low-code tools to train custom ML models on structured data, text, or images. It's backed by Google's AI expertise, making it scalable and reliable for quick prototypes. Usage Across Domains: Fintech: Predict loan defaults from applicant data (e.g., income, credit score) with a classification model. Cybersecurity: Detect anomalies in access logs (e.g., user ID, timestamp) to identify breaches. Healthcare: Classify patient risk levels from structured EHR data (e.g., BP, cholesterol). Social Media: Predict ad engagement from user demographics and interaction history. Social Cause: Forecast disaster relief needs using weather data and population stats. Free Status: Free tier with $300 Google Cloud credit; pay-as-you-go after (e.g., $0.10/hour training). Website: cloud.google.com/automl Integration: Cloud API, Google Sheets, Data Studio for visualizations. 3. DataRobot (No-Code/Low-Code) Description: DataRobot is an enterprise-grade AutoML platform that automates model building, evaluation, and deployment. It's powerful for handling large datasets and offers built-in visualizations, though it's less accessible for solo hackers due to cost. Usage Across Domains: Fintech: Build a fraud detection system for credit card transactions with risk scores and explanations. Cybersecurity: Predict insider threats by analyzing employee activity logs (e.g., login times, file access). Healthcare: Score disease risks from lab results and patient history. Social Media: Forecast user retention based on",
"source": "User Input",
"type": "text",
"timestamp": "4300e2aa-6168-4c5f-973e-38909a65ce0b"
},
{
"text": "engagement metrics. Social Cause: Optimize resource allocation for relief efforts using past campaign data. Free Status: No free tier; enterprise pricing (contact sales, typically $1000s/month). Website: datarobot.com Integration: REST API, native dashboards, Power BI for UI. 4. Obviously AI (No-Code) Description: Obviously AI is a no-code platform focused on predictive analytics and time-series forecasting. It's designed for simplicity, allowing one-click model training on structured data, making it ideal for quick hackathon wins. Usage Across Domains: Fintech: Predict customer churn from banking logs (e.g., withdrawals, account age). Cybersecurity: Forecast potential breaches based on historical attack frequencies. Healthcare: Estimate patient recovery times from treatment data. Social Media: Predict post engagement trends over time (e.g., likes, shares). Social Cause: Model future donation inflows for campaign planning. Free Status: Free tier (500 predictions); paid plans start at $99/month. Website: obviously.ai Integration: REST API, CSV exports, Appsmith or Google Sheets for UI. 5. Create ML (No-Code) Description: Create ML, by Apple, is a no-code tool within Xcode for training ML models on tabular data, images, or sounds. It's Mac-only but offers a polished interface for Apple ecosystem users. Usage Across Domains: Fintech: Classify transaction risk levels from structured data (e.g., amount, location). Cybersecurity: Detect unusual login patterns from user logs. Healthcare: Predict patient outcomes from vital signs. Social Media: Analyze audio engagement (e.g., podcast listens). Social Cause: Forecast volunteer turnout from event data. Free Status: Yes, fully free (requires macOS and Xcode). Website: developer.apple.com/machine-learning/create-ml/ Integration: Export to Core ML, use in Swift apps or Bubble via API. 6. BigML (No-Code/Low-Code) Description: BigML is a no-code/low-code platform for ML tasks like classification, regression, and clustering. It offers a visual interface for model building and deployment, with strong support for structured data. Usage Across Domains: Fintech: Detect payment fraud with decision tree models. Cybersecurity: Cluster network traffic to spot anomalies. Healthcare: Predict disease progression from patient records. Social Media: Classify user sentiment from engagement data. Social Cause: Analyze donation patterns for resource planning. Free Status: Free tier (1MB data limit); paid plans start at $30/month. Website: bigml.com Integration: REST API, CSV exports, Softr or Airtable for UI. 7. H2O.ai (No-Code/Low-Code) Description: H2O.ai provides a no-code/low-code AutoML platform for predictive modeling, with a focus on scalability and enterprise use. Its Driverless AI automates ML workflows with minimal input. Usage Across Domains: Fintech: Predict stock price movements from historical data. Cybersecurity: Detect phishing attempts from email metadata. Healthcare: Forecast patient readmissions with high accuracy. Social Media: Predict influencer impact from metrics. Social Cause: Optimize disaster relief logistics with predictive models. Free Status: Free tier (limited features); paid plans start at $300/month. Website: h2o.ai Integration: REST API, native dashboards, Google Sheets for UI. Deep Learning (DL) Tools Tools for neural networks, image recognition, and complex data processing with minimal coding. 8. Lobe (No-Code) Description: Lobe is a free, no-code desktop app by Microsoft for training image-based DL models. It's intuitive, runs locally, and is perfect for visual tasks without coding. Usage Across Domains: Fintech: Detect forged checks or signatures in",
"source": "User Input",
"type": "text",
"timestamp": "05325c93-12a5-45f3-8bdd-86aaba5b36a2"
},
{
"text": "scanned images. Cybersecurity: Identify malware from visual execution screenshots. Healthcare: Classify X-rays for disease detection (e.g., pneumonia). Social Media: Recognize inappropriate images in posts. Social Cause: Spot environmental damage in photos (e.g., oil spills). Free Status: Yes, fully free. Website: lobe.ai Integration: Native app UI, export to TensorFlow.js, Thunkable for mobile UI. 9. Teachable Machine (No-Code) Description: Teachable Machine is a web-based no-code tool by Google for training DL models on images, audio, or poses. It's browser-based, requiring no setup, and ideal for quick demos. Usage Across Domains: Fintech: Classify handwritten financial forms for fraud detection. Cybersecurity: Detect malware audio signatures from execution sounds. Healthcare: Identify distress gestures in patient videos. Social Media: Classify meme images for moderation. Social Cause: Recognize disaster-affected areas in photos. Free Status: Yes, fully free. Website: teachablemachine.withgoogle.com Integration: Export to TensorFlow.js, Glitch for web UI. 10. RunwayML (No-Code, DL Features) Description: RunwayML offers no-code DL capabilities alongside generative features, supporting image/video recognition and editing with pre-trained models. Usage Across Domains: Fintech: Detect anomalies in financial document scans. Cybersecurity: Classify malicious image attachments. Healthcare: Analyze medical images for anomalies. Social Media: Recognize video content for moderation. Social Cause: Identify disaster damage in video footage. Free Status: Free tier (125 credits); paid plans start at $15/month. Website: runwayml.com Integration: Web UI, exportable outputs, Zapier for automation. 11. Clarifai (No-Code/Low-Code) Description: Clarifai is a no-code/low-code platform for DL, specializing in image, video, and text recognition with pre-built and custom models. Usage Across Domains: Fintech: Verify identity documents for security. Cybersecurity: Detect phishing images in emails. Healthcare: Classify medical scans (e.g., tumors). Social Media: Identify harmful video content. Social Cause: Recognize environmental threats in images. Free Status: Free tier (5,000 operations/month); paid plans start at $30/month. Website: clarifai.com Integration: REST API, Bubble or Softr for UI. 12. Nanonets (No-Code) Description: Nanonets is a no-code platform for DL-based image and document processing, excelling at OCR and object detection with a simple interface. Usage Across Domains: Fintech: Extract data from invoices to detect fraud. Cybersecurity: Identify fake credentials in scanned documents. Healthcare: Process medical forms for digitization. Social Media: Detect branded content in images. Social Cause: Extract info from disaster relief forms. Free Status: Free tier (100 images/month); paid plans start at $99/month. Website: nanonets.com Integration: REST API, Airtable or Google Sheets for UI. Natural Language Processing (NLP) Tools Tools for text analysis, sentiment, classification, and conversational AI with minimal coding. 13. MonkeyLearn (No-Code) Description: MonkeyLearn is a no-code NLP platform for text classification, sentiment analysis, and entity extraction. It's user-friendly and perfect for quick text-based AI agents. Usage Across Domains: Fintech: Analyze customer emails for fraud reports. Cybersecurity: Classify phishing emails from content. Healthcare: Extract symptoms from patient feedback. Social Media: Identify toxic comments in posts. Social Cause: Process disaster relief requests from text. Free Status: Free tier (100 queries/month); paid plans start at $299/month. Website: monkeylearn.com Integration: REST API, webhooks, Airtable or Slack for UI. 14. Levity (No-Code) Description: Levity is a no-code tool for text, image, and document",
"source": "User Input",
"type": "text",
"timestamp": "e25d8c2d-de47-4d74-ad49-263fdfdc4d14"
},
{
"text": "classification, with automation features to streamline repetitive tasks. Usage Across Domains: Fintech: Classify scam reports from customer texts. Cybersecurity: Detect bot-generated text in logs. Healthcare: Analyze doctor's notes for insights. Social Media: Flag harmful comments or posts. Social Cause: Process volunteer applications for sentiment. Free Status: Free tier (50 classifications/month); paid plans start at $49/month. Website: levity.ai Integration: API, Google Sheets, Zapier for UI. 15. Cogniflow (No-Code) Description: Cogniflow is a no-code platform for text, image, and audio analysis, allowing custom NLP models with an easy-to-use interface. Usage Across Domains: Fintech: Analyze reviews for fraud signals. Cybersecurity: Detect threats in chat logs. Healthcare: Extract insights from audio patient interviews. Social Media: Classify post sentiment. Social Cause: Process disaster reports from voice data. Free Status: Free tier (limited usage); paid plans start at $29/month. Website: cogniflow.ai Integration: REST API, CSV exports, Softr for UI. 16. TextRazor (No-Code/Low-Code) Description: TextRazor is a no-code/low-code NLP tool for entity extraction, sentiment analysis, and topic modeling, with API-driven functionality. Usage Across Domains: Fintech: Extract entities (e.g., names, amounts) from financial reports. Cybersecurity: Analyze threat intelligence texts. Healthcare: Parse patient notes for key terms. Social Media: Assess post topics and sentiment. Social Cause: Extract needs from relief texts. Free Status: Free tier (500 calls/day); paid plans start at $79/month. Website: textrazor.com Integration: REST API, Bubble or Airtable for UI. 17. Dialogflow (No-Code/Low-Code) Description: Dialogflow, by Google, is a no-code/low-code platform for building conversational AI agents (chatbots) with natural language understanding. Usage Across Domains: Fintech: Create a chatbot for fraud reporting. Cybersecurity: Build a bot to guide users on phishing alerts. Healthcare: Design a patient symptom checker. Social Media: Automate user query responses. Social Cause: Coordinate volunteer sign-ups via chat. Free Status: Free tier (unlimited text requests); paid plans start at $0.002/request for advanced features. Website: dialogflow.cloud.google.com Integration: API, Google Assistant, Slack for UI. 18. Wit.ai (No-Code) Description: Wit.ai, by Facebook, is a no-code platform for building NLP-powered chatbots and voice assistants with a simple interface. Usage Across Domains: Fintech: Chatbot for transaction inquiries. Cybersecurity: Bot to report suspicious activity. Healthcare: Voice assistant for patient triage. Social Media: Automate content moderation queries. Social Cause: Chatbot for disaster relief coordination. Free Status: Yes, fully free (open-source by Meta). Website: wit.ai Integration: API, Facebook Messenger, Bubble for UI. Generative AI (GenAI) Tools Tools for creating content, simulations, or synthetic data with minimal coding. 19. RunwayML (No-Code) Description: RunwayML is a no-code platform for generative AI, offering tools to create images, videos, and text using pre-trained models, with an emphasis on creativity. Usage Across Domains: Fintech: Generate synthetic transaction data for testing. Cybersecurity: Simulate phishing emails for training. Healthcare: Create patient education visuals. Social Media: Produce viral memes or videos. Social Cause: Generate disaster awareness graphics. Free Status: Free tier (125 credits); paid plans start at $15/month. Website: runwayml.com Integration: Web UI, exportable outputs, Zapier for automation. 20. E42 (No-Code) Description: E42 is a no-code platform for building AI assistants and automating workflows, with a focus on conversational and generative",
"source": "User Input",
"type": "text",
"timestamp": "bcf38e40-92b7-4624-b39e-a514857c8812"
},
{
"text": "AI. Usage Across Domains: Fintech: Automate fraud reporting responses. Cybersecurity: Simulate ransomware negotiation scripts. Healthcare: Generate patient follow-up messages. Social Media: Auto-reply to user inquiries. Social Cause: Coordinate volunteer responses. Free Status: No free tier; custom pricing (contact sales). Website: e42.ai Integration: Native chatbot UI, API, Slack integration. 21. Synthesia (No-Code) Description: Synthesia is a no-code tool for generating AI-powered videos with synthetic avatars, ideal for presentations or training content. Usage Across Domains: Fintech: Create fraud prevention training videos. Cybersecurity: Generate cybersecurity awareness clips. Healthcare: Produce patient education videos. Social Media: Make branded video content. Social Cause: Develop disaster preparedness tutorials. Free Status: Free tier (10 minutes of video); paid plans start at $22/month. Website: synthesia.io Integration: Web UI, exportable videos, Bubble for hosting. 22. Canva Magic Studio (No-Code) Description: Canva's Magic Studio is a no-code GenAI suite within Canva, offering text-to-image, text generation, and design tools for visual content creation. Usage Across Domains: Fintech: Design financial infographics. Cybersecurity: Create phishing awareness posters. Healthcare: Generate medical flyers. Social Media: Produce eye-catching posts. Social Cause: Design campaign visuals. Free Status: Free tier (limited features); Canva Pro starts at $12.99/month. Website: canva.com/magic-studio Integration: Web UI, exportable designs, Airtable for storage. 23. Writesonic (No-Code) Description: Writesonic is a no-code GenAI tool for generating text content (e.g., articles, ads) with AI-driven templates and prompts. Usage Across Domains: Fintech: Write financial advice blogs. Cybersecurity: Generate security alert messages. Healthcare: Create patient newsletters. Social Media: Produce post captions. Social Cause: Draft fundraising appeals. Free Status: Free tier (10,000 words/month); paid plans start at $12.67/month. Website: writesonic.com Integration: Web UI, export to docs, Slack for sharing. 24. Jasper (No-Code) Description: Jasper is a no-code GenAI platform for creating high-quality text content, with templates for marketing, blogs, and more. Usage Across Domains: Fintech: Generate investment guides. Cybersecurity: Write phishing prevention tips. Healthcare: Create health awareness content. Social Media: Craft engaging posts. Social Cause: Produce charity campaign scripts. Free Status: No free tier; paid plans start at $39/month. Website: jasper.ai Integration: Web UI, export to docs, Google Drive integration. Database Management Tools Tools for storing, organizing, and managing data with minimal coding. 25. Airtable (No-Code) Description: Airtable is a no-code database with a spreadsheet-like interface, offering flexibility for structured data, collaboration, and automation. Usage Across Domains: Fintech: Store transaction logs for fraud analysis. Cybersecurity: Track threat incidents with details. Healthcare: Manage patient records for predictions. Social Media: Log user engagement metrics. Social Cause: Organize volunteer schedules. Free Status: Free tier (1,200 records/base); paid plans start at $10/month. Website: airtable.com Integration: API, Softr for UI, Zapier for automation. 26. Google Sheets (No-Code) Description: Google Sheets is a free, cloud-based spreadsheet tool with automation and collaboration features, ideal for lightweight data management. Usage Across Domains: Fintech: Log financial data for analysis. Cybersecurity: Store attack logs for monitoring. Healthcare: Track patient stats for ML. Social Media: Record post performance. Social Cause: Manage donation records. Free Status: Yes, fully free with Google account. Website: sheets.google.com Integration: Google Data Studio, Appsheet, Zapier. 27. Notion",
"source": "User Input",
"type": "text",
"timestamp": "6c5bed06-c4e8-432f-b504-9840f88a143f"
},
{
"text": "(No-Code) Description: Notion is a no-code workspace tool with database capabilities, allowing structured and unstructured data management in a flexible format. Usage Across Domains: Fintech: Store financial project data. Cybersecurity: Track security incidents. Healthcare: Manage patient research notes. Social Media: Log campaign plans. Social Cause: Organize relief effort details. Free Status: Free tier (unlimited blocks for individuals); paid plans start at $8/month. Website: notion.so Integration: API, Softr for UI, Zapier for automation. 28. Bubble Data (No-Code) Description: Bubble Data is the built-in database feature of Bubble, a no-code app builder, allowing data storage and management within web apps. Usage Across Domains: Fintech: Store user transaction histories. Cybersecurity: Log threat alerts. Healthcare: Manage patient profiles. Social Media: Track user interactions. Social Cause: Store volunteer data. Free Status: Free tier",
"source": "User Input",
"type": "text",
"timestamp": "74fe4de7-beae-44ca-af7e-fe9498dbb535"
},
{
"text": "By signing in, you agree to Neetcode's terms of service and privacy policy. Choose the font size of the editor. Update the default tab size of the editor. Switch to Vim key bindings. Are you sure you want to reset the code? Python (3.13.2) Python does not have built-inTree SetorTree Mapdata structures so you may usepython-sortedcontainersinstead.",
"source": "https://neetcode.io/problems/longest-repeating-substring-with-replacement?list=neetcode150",
"type": "web",
"timestamp": "9c3567c0-6c46-4732-aac7-4acc0e7a96f4"
},
{
"text": "Illustrated guide to SQLXsqlxis a package for Go which provides a set of extensions on top of the excellent built-indatabase/sqlpackage.ExaminingGoidioms is the focus of this document, so there is no presumption being made that anySQLherein is actually a recommended way to use a database. It will not cover setting up a Go development environment, basic Go information about syntax or semantics, or SQL itself.Finally, the standarderrvariable will be used to indicate that errors are being returned, but for brevity they will be ignored. You should make sure to check all errors in an actual program.Resources\u00b6There are other resources of excellent information about using SQL in Go:database/sql documentationgo-database-sql tutorialIf you need help getting started with Go itself, I recommend these resources:The Go tourHow to write Go codeEffective GoBecause thedatabase/sqlinterface is a subset of sqlx, all of the advice in these documents aboutdatabase/sqlusage also apply to usage of sqlx.Getting Started\u00b6You will want to installsqlxand a database driver. Since it's infrastructureless, I recommend mattn's sqlite3 driver to start out with:$ gogetgithub.com/jmoiron/sqlx$ gogetgithub.com/mattn/go-sqlite3Handle Types\u00b6sqlxis intended to have the samefeelasdatabase/sql. There are 4 mainhandletypes:sqlx.DB- analagous tosql.DB, a representation of a databasesqlx.Tx- analagous tosql.Tx, a representation of a transactionsqlx.Stmt- analagous tosql.Stmt, a representation of a prepared statementsqlx.NamedStmt- a representation of a prepared statement with support fornamed parametersHandle types allembedtheirdatabase/sqlequivalents, meaning that when you callsqlx.DB.Query, you are calling thesamecode assql.DB.Query. This makes it easy to introduce into an existing codebase.In addition to these, there are 2cursortypes:sqlx.Rows- analagous tosql.Rows, a cursor returned fromQueryxsqlx.Row- analagous tosql.Row, a result returned fromQueryRowxAs with the handle types,sqlx.Rowsembedssql.Rows. Because the underlying implementation was inaccessible,sqlx.Rowis a partial re-implementation ofsql.Rowthat retains the standard interface.Connecting to Your Database\u00b6ADBinstance isnota connection, but an abstraction representing a Database. This is why creating a DB does not return an error and will not panic. It maintains aconnection poolinternally, and will attempt to connect when a connection is first needed. You can create an sqlx.DB viaOpenor by creating a new sqlx DB handle from an existing sql.DB viaNewDb:vardb*sqlx.DB// exactly the same as the built-indb=sqlx.Open(\"sqlite3\",\":memory:\")// from a pre-existing sql.DB; note the required driverNamedb=sqlx.NewDb(sql.Open(\"sqlite3\",\":memory:\"),\"sqlite3\")// force a connection and test that it workederr=db.Ping()In some situations, you might want to open a DB and connect at the same time; for instance, in order to catch configuration issues during your initialization phase. You can do this in one go withConnect, which Opens a new DB and attempts aPing. TheMustConnectvariant will panic when encountering an error, suitable for use at the module level of your package.varerr error// open and connect at the same time:db,err=sqlx.Connect(\"sqlite3\",\":memory:\")// open and connect at the same time, panicing on errordb=sqlx.MustConnect(\"sqlite3\",\":memory:\")Querying 101\u00b6The handle types in sqlx implement the same basic verbs for querying your database:Exec(...) (sql.Result, error)- unchanged from database/sqlQuery(...) (*sql.Rows, error)- unchanged from database/sqlQueryRow(...) *sql.Row- unchanged from database/sqlThese extensions to the built-in verbs:MustExec() sql.Result-- Exec, but panic on errorQueryx(...) (*sqlx.Rows, error)- Query, but return an sqlx.RowsQueryRowx(...) *sqlx.Row-- QueryRow, but return an sqlx.RowAnd these new semantics:Get(dest interface{}, ...) errorSelect(dest interface{}, ...) errorLet's go from the unchanged interface through the new semantics, explaining their",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "d7f666b8-f827-49f3-883b-ba8de27b5317"
},
{
"text": "use.Exec\u00b6Exec and MustExec get a connection from the connection pool and executes the provided query on the server. For drivers that do not support ad-hoc query execution, a prepared statementmaybe created behind the scenes to be executed. The connection is returned to the pool before the result is returned.schema:=`CREATE TABLE place (country text,city text NULL,telcode integer);`// execute a query on the serverresult,err:=db.Exec(schema)// or, you can use MustExec, which panics on errorcityState:=`INSERT INTO place (country, telcode) VALUES (?, ?)`countryCity:=`INSERT INTO place (country, city, telcode) VALUES (?, ?, ?)`db.MustExec(cityState,\"Hong Kong\",852)db.MustExec(cityState,\"Singapore\",65)db.MustExec(countryCity,\"South Africa\",\"Johannesburg\",27)Theresulthas two possible pieces of data:LastInsertId()orRowsAffected(), the availability of which is driver dependent. In MySQL, for instance,LastInsertId()will be available on inserts with an auto-increment key, but in PostgreSQL, this information can only be retrieved from a normal row cursor by using theRETURNINGclause.bindvars\u00b6The?query placeholders, calledbindvarsinternally, are important; you shouldalwaysuse these to send values to the database, as they will preventSQL injectionattacks. database/sql does not attemptanyvalidation on the query text; it is sent to the server as is, along with the encoded parameters. Unless drivers implement a special interface, the query is prepared on the server first before execution. Bindvars are therefore database specific:MySQL uses the?variant shown abovePostgreSQL uses an enumerated$1,$2, etc bindvar syntaxSQLite accepts both?and$1syntaxOracle uses a:namesyntaxOther databases may vary. You can use thesqlx.DB.Rebind(string) stringfunction with the?bindvar syntax to get a query which is suitable for execution on your current database type.A common misconception with bindvars is that they are used for interpolation. They are only forparameterization, and are not allowed tochange the structure of an SQL statement. For instance, using bindvars to try and parameterize column or table names will not work:// doesn't workdb.Query(\"SELECT * FROM ?\",\"mytable\")// also doesn't workdb.Query(\"SELECT ?, ? FROM people\",\"name\",\"location\")Query\u00b6Query is the primary way to run queries with database/sql that return row results. Query returns ansql.Rowsobject and an error:// fetch all places from the dbrows,err:=db.Query(\"SELECT country, city, telcode FROM place\")// iterate over each rowforrows.Next(){varcountrystring// note that city can be NULL, so we use the NullString typevarcity sql.NullStringvartelcodeinterr=rows.Scan(&country,&city,&telcode)}// check the error from rowserr=rows.Err()You should treat the Rows like a database cursor rather than a materialized list of results. Although driver buffering behavior can vary, iterating viaNext()is a good way to bound the memory usage of large result sets, as you're only scanning a single row at a time.Scan()usesreflectto map sql column return types to Go types likestring,[]byte, et al. If you do not iterate over a whole rows result, be sure to callrows.Close()to return the connection back to the pool!The error returned by Query is any error that might have happened while preparing or executing on the server. This can include grabbing a bad connection from the pool, although database/sql willretry 10 timesto attempt to find or create a working connection. Generally, the error will be due to bad SQL syntax, type mismatches, or incorrect field and table names.In most cases, Rows.Scan will copy the data it gets from the driver, as it is not aware of how the driver may reuse its buffers. The special typesql.RawBytescan be used",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "1ed54cc3-c403-4ee9-b128-57a764e4c988"
},
{
"text": "to get azero-copyslice of bytes from the actual data returned by the driver. After the next call to Next(), such a value is no longer valid, as that memory might have been overwritten by the driver.The connection used by the Query remains active untileitherall rows are exhausted by the iteration via Next, orrows.Close()is called, at which point it is released. For more information, see the section onthe connection pool.The sqlx extensionQueryxbehaves exactly as Query does, but returns ansqlx.Rows, which has extended scanning behaviors:typePlacestruct{CountrystringCitysql.NullStringTelephoneCodeint`db:\"telcode\"`}rows,err:=db.Queryx(\"SELECT * FROM place\")forrows.Next(){varpPlaceerr=rows.StructScan(&p)}The primary extension on sqlx.Rows isStructScan(), which automatically scans results into struct fields. Note that the fields must beexported(capitalized) in order for sqlx to be able to write into them, something true ofallmarshallers in Go. You can use thedbstruct tag to specify which column name maps to each struct field, or set a new default mapping withdb.MapperFunc(). The default behavior is to usestrings.Loweron the field name to match against the column names. For more information aboutStructScan,SliceScan, andMapScan, see thesection on advanced scanning.QueryRow\u00b6QueryRow fetches one row from the server. It takes a connection from the connection pool and executes the query using Query, returning aRowobject which has its own internal Rows object:row:=db.QueryRow(\"SELECT * FROM place WHERE telcode=?\",852)vartelcodeinterr=row.Scan(&telcode)Unlike Query, QueryRow returns a Row type result with no error, making it safe to chain the Scan off of the return. If there was an error executing the query, that error is returned by Scan. If there are no rows, Scan returnssql.ErrNoRows. If the scan itself fails (eg. due to type mismatch), that error is also returned.The Rows struct internal to the Row result is Closed upon Scan, meaning that the connection used by QueryRow is kept open until the result is scanned. It also means thatsql.RawBytesis not usable here, since the referenced memory belongs to the driver and may already be invalid by the time control is returned to the caller.The sqlx extensionQueryRowxwill return an sqlx.Row instead of an sql.Row, and it implements the same scanning extensions as Rows, outlined above and in theadvanced scanning section:varpPlaceerr:=db.QueryRowx(\"SELECT city, telcode FROM place LIMIT 1\").StructScan(&p)Get and Select\u00b6GetandSelectare time saving extensions to the handle types. They combine the execution of a query with flexible scanning semantics. To explain them clearly, we have to talk about what it means to bescannable:a value is scannable if it is not a struct, egstring,inta value is scannable if it implementssql.Scannera value is scannable if it is a struct with no exported fields (eg.time.Time)GetandSelectuserows.Scanon scannable types androws.StructScanon non-scannable types. They are roughly analagous toQueryRowandQuery, where Get is useful for fetching a single result and scanning it, and Select is useful for fetching a slice of results:p:=Place{}pp:=[]Place{}// this will pull the first place directly into perr=db.Get(&p,\"SELECT * FROM place LIMIT 1\")// this will pull places with telcode > 50 into the slice pperr=db.Select(&pp,\"SELECT * FROM place WHERE telcode > ?\",50)// they work with regular types as wellvaridinterr=db.Get(&id,\"SELECT count(*) FROM place\")// fetch at most 10 place namesvarnames[]stringerr=db.Select(&names,\"SELECT name FROM place LIMIT 10\")Get and Select both will close the Rows",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "2dad321a-dcd7-4866-ab5c-1fa503ce41b5"
},
{
"text": "they create during query execution, and will return any error encountered at any step of the process. Since they use StructScan internally, the details in theadvanced scanning sectionalso apply to Get and Select.Select can save you a lot of typing, but beware! It's semantically different fromQueryx, since it will load the entire result set into memory at once. If that set is not bounded by your query to some reasonable size, it might be best to use the classic Queryx/StructScan iteration instead.Transactions\u00b6To use transactions, you must create a transaction handle withDB.Begin(). Code like thiswill not work:// this will not work if connection pool > 1db.MustExec(\"BEGIN;\")db.MustExec(...)db.MustExec(\"COMMIT;\")Remember, Exec and all other query verbs will ask the DB for a connection and then return it to the pool each time. There's no guarantee that you will receive the same connection that the BEGIN statement was executed on. To use transactions, you must therefore useDB.Begin()tx,err:=db.Begin()err=tx.Exec(...)err=tx.Commit()The DB handle also has the extensionsBeginx()andMustBegin(), which return ansqlx.Txinstead of ansql.Tx:tx:=db.MustBegin()tx.MustExec(...)err=tx.Commit()sqlx.Txhas all of the handle extensions thatsqlx.DBhas.Since transactions are connection state, the Tx object must bind and control a single connection from the pool. A Tx will maintain that single connection for its entire life cycle, releasing it only whenCommit()orRollback()is called. You should take care to call at least one of these, or else the connection will be held until garbage collection.Because you only have one connection to use in a transaction, you can only execute one statement at a time; the cursor types Row and Rows must be Scanned or Closed, respectively, before executing another query. If you attempt to send the server data while it is sending you a result, it can potentially corrupt the connection.Finally, Tx objects do not actually imply any behavior on the server; they merely execute a BEGIN statement and bind a single connection. The actual behavior of the transaction, including things like locking andisolation, is completely unspecified and database dependent.Prepared Statements\u00b6On most databases, statements will actually be prepared behind the scenes whenever a query is executed. However, you may also explicitly prepare statements for reuse elsewhere withsqlx.DB.Prepare():stmt,err:=db.Prepare(`SELECT * FROM place WHERE telcode=?`)row=stmt.QueryRow(65)tx,err:=db.Begin()txStmt,err:=tx.Prepare(`SELECT * FROM place WHERE telcode=?`)row=txStmt.QueryRow(852)Prepare actually runs the preparation on the database, so it requires a connection and its connection state. database/sql abstracts this from you, allowing you to execute from a single Stmt object concurrently on many connections by creating the statements on new connections automatically.Preparex(), which returns ansqlx.Stmtwhich has all of the handle extensions that sqlx.DB and sqlx.Tx do:stmt,err:=db.Preparex(`SELECT * FROM place WHERE telcode=?`)varpPlaceerr=stmt.Get(&p,852)The standard sql.Tx object also has aStmt()method which returns a transaction-specific statement from a pre-existing one. sqlx.Tx has aStmtxversion which will create a new transaction specificsqlx.Stmtfrom an existing sql.Stmtorsqlx.Stmt.Query HelpersThedatabase/sqlpackage does not do anything with your actual query text. This makes it trivial to use backend-specific features in your code; you can write queries just as you would write them in your database prompt. While this is very flexible, it makes writing certain kinds of queries difficult.\"In\" Queries\u00b6Becausedatabase/sqldoes not inspect your query and it passes",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "117576b5-8288-4af1-9b74-5da7eecfbfbb"
},
{
"text": "your arguments directly to the driver, it makes dealing with queries with IN clauses difficult:SELECT*FROM users WHERE level IN(?);When this gets prepared as a statement on the backend, the bindvar?will only correspond to asingleargument, but what is often desired is for that to be a variable number of arguments depending on the length of some slice, eg:varlevels=[]int{4,6,7}rows,err:=db.Query(\"SELECT * FROM users WHERE level IN (?);\",levels)This pattern is possible by first processing the query withsqlx.In:varlevels=[]int{4,6,7}query,args,err:=sqlx.In(\"SELECT * FROM users WHERE level IN (?);\",levels)// sqlx.In returns queries with the `?` bindvar, we can rebind it for our backendquery=db.Rebind(query)rows,err:=db.Query(query,args...)Whatsqlx.Indoes is expand any bindvars in the query passed to it that correspond to a slice in the arguments to the length of that slice, and then append those slice elements to a new arglist. It does this with the?bindvar only; you can usedb.Rebindto get a query suitable for your backend.Named Queries\u00b6Named queries are common to many other database packages. They allow you to use a bindvar syntax which refers to the names of struct fields or map keys to bind variables a query, rather than having to refer to everything positionally. The struct field naming conventions follow that ofStructScan, using theNameMapperand thedbstruct tag. There are two extra query verbs related to named queries:NamedQuery(...) (*sqlx.Rows, error)- like Queryx, but with named bindvarsNamedExec(...) (sql.Result, error)- like Exec, but with named bindvarsAnd one extra handle type:NamedStmt- an sqlx.Stmt which can be prepared with named bindvars// named query with a structp:=Place{Country:\"South Africa\"}rows,err:=db.NamedQuery(`SELECT * FROM place WHERE country=:country`,p)// named query with a mapm:=map[string]interface{}{\"city\":\"Johannesburg\"}result,err:=db.NamedExec(`SELECT * FROM place WHERE city=:city`,m)Named query execution and preparation works off both structs and maps. If you desire the full set of query verbs, prepare a named statement and use that instead:p:=Place{TelephoneCode:50}pp:=[]Place{}// select all telcodes > 50nstmt,err:=db.PrepareNamed(`SELECT * FROM place WHERE telcode > :telcode`)err=nstmt.Select(&pp,p)Named query support is implemented by parsing the query for the:paramsyntax and replacing it with the bindvar supported by the underlying database, then performing the mapping at execution, so it is usable on any database that sqlx supports. You can also usesqlx.Named, which uses the?bindvar, and can be composed withsqlx.In:arg:=map[string]interface{}{\"published\":true,\"authors\":[]{8,19,32,44},}query,args,err:=sqlx.Named(\"SELECT * FROM articles WHERE published=:published AND author_id IN (:authors)\",arg)query,args,err:=sqlx.In(query,args...)query=db.Rebind(query)db.Query(query,args...)Advanced Scanning\u00b6StructScanis deceptively sophisticated. It supports embedded structs, and assigns to fields using the same precedence rules that Go uses for embedded attribute and method access. A common use of this is sharing common parts of a table model among many tables, eg:typeAutoIncrstruct{ID uint64Createdtime.Time}typePlacestruct{AddressstringAutoIncr}typePersonstruct{NamestringAutoIncr}With the structs above, Person and Place will both be able to receiveidandcreatedcolumns from a StructScan, because they embed theAutoIncrstruct which defines them. This feature can enable you to quickly create an ad-hoc table for joins. It works recursively as well; the following will have the Person's Name and its AutoIncr ID and Created fields accessible, both via the Go dot operator and via StructScan:typeEmployeestruct{BossIDuint64EmployeeIDuint64Person}Note that sqlx historically supported this feature for non-embedded structs, this ended up being confusing because users were using this feature to define relationships and embedding the same structs twice:typeChildstruct{FatherPersonMotherPerson}This causes some problems. In Go, it's legal to shadow descendent",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "f3381d4a-a5fe-479e-a6e9-7d564feeef23"
},
{
"text": "fields; if Employee from the embedded example defined aName, it would take precedence over the Person's Name. Butambiguousselectors are illegal and causea runtime error. If we wanted to create a quick JOIN type for Person and Place, where would we put theidcolumn, which is defined in both via their embedded AutoIncr? Would there be an error?Because of the way that sqlx builds the mapping of field name to field address, by the time you Scan into a struct, it no longer knows whether or not a name was encountered twice during its traversal of the struct tree. So unlike Go, StructScan will choose the \"first\" field encountered which has that name. Since Go struct fields are ordered from top to bottom, and sqlx does a breadth-first traversal in order to maintain precedence rules, it would happen in the shallowest, top-most definition. For example, in the type:typePersonPlacestruct{PersonPlace}A StructScan will set anidcolumn result inPerson.AutoIncr.ID, also accessible asPerson.ID. To avoid confusion, it's suggested that you useASto create column aliases in your SQL instead.Scan Destination Safety\u00b6By default, StructScan will return an error if a column does not map to a field in the destination. This mimics the treatment for things like unused variables in Go, but doesnotmatch the way that standard library marshallers likeencoding/jsonbehave. Because SQL is generally executed in a more controlled fashion than parsing JSON, and these errors are generally coding errors, a decision was made to return errors by default.Like unused variables, columns which you ignore are a waste of network and database resources, and detecting things like an incompatible mapping or a typo in a struct tag early can be difficult without the mapper letting you know something wasn't found.Despite this, there are some cases where ignoring columns with no destination might be desired. For this, there is theUnsafemethod on eachHandle typewhich returns a new copy of that handle with this safety turned off:varpPerson// err here is not nil because there are no field destinations for columns in `place`err=db.Get(&p,\"SELECT * FROM person, place LIMIT 1;\")// this will NOT return an error, even though place columns have no destinationudb:=db.Unsafe()err=udb.Get(&p,\"SELECT * FROM person, place LIMIT 1;\")Controlling Name Mapping\u00b6Struct fields used as targets for StructScansmustbe capitalized in order to be accessible by sqlx. Because of this, sqlx uses aNameMapperwhich appliesstrings.ToLowerto field names to map them to columns in your rows result. This isn't always desirable, depending on your schema, so sqlx allows the mapping to be customized a number of ways.The simplest of these ways is to set it for a db handle by usingsqlx.DB.MapperFunc, which receives an argument of typefunc(string) string. If your library requires a particular mapper, and you don't want to poison thesqlx.DByou receive, you can create a copy for use in the library to ensure a particular default mapping:// if our db schema uses ALLCAPS columns, we can use normal fieldsdb.MapperFunc(strings.ToUpper)// suppose a library uses lowercase columns, we can create a copycopy:=sqlx.NewDb(db.DB,db.DriverName())copy.MapperFunc(strings.ToLower)Eachsqlx.DBuses thesqlx/reflectxpackage'sMapperto achieve this mapping underneath, and exposes the active mapper assqlx.DB.Mapper. You can further customize the mapping",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "3174b7fe-52e4-4525-80a0-0a4dbbcbc13d"
},
{
"text": "on a DB by setting it directly:import\"github.com/jmoiron/sqlx/reflectx\"// Create a new mapper which will use the struct field tag \"json\" instead of \"db\"db.Mapper=reflectx.NewMapperFunc(\"json\",strings.ToLower)Alternate Scan Types\u00b6In addition to using Scan and StructScan, an sqlx Row or Rows can be used to automatically return a slice or a map of results:rows,err:=db.Queryx(\"SELECT * FROM place\")forrows.Next(){// cols is an []interface{} of all of the column resultscols,err:=rows.SliceScan()}rows,err:=db.Queryx(\"SELECT * FROM place\")forrows.Next(){results:=make(map[string]interface{})err=rows.MapScan(results)}SliceScan returns an[]interface{}of all columns, which can be useful insituationswhere you are executing queries on behalf of a third party and have no way of knowing what columns may be returned. MapScan behaves the same way, but maps the column names to interface{} values. An important caveat here is that the results returned byrows.Columns()does not include fully qualified names, such thatSELECT a.id, b.id FROM a NATURAL JOIN bwill result in a Columns result of[]string{\"id\", \"id\"}, clobbering one of the results in your map.Custom Types\u00b6The examples above all used the built-in types to both scan and query with, but database/sql provides interfaces to allow you to use any custom types:sql.Scannerallows you to use custom types in a Scan()driver.Valuerallows you to use custom types in a Query/QueryRow/ExecThese are the standard interfaces, and using them will ensure portability to any library that might be providing services on top of database/sql. For a detailed look at how to use them,read this blog postor check out thesqlx/typespackage, which implements a few standard useful types.The Connection Pool\u00b6Statement preparation and query execution require a connection, and the DB object will manage a pool of them so that it can be safely used for concurrent querying. There are two ways to control the size of the connection pool as of Go 1.2:DB.SetMaxIdleConns(n int)DB.SetMaxOpenConns(n int)By default, the pool grows unbounded, and connections will be created whenever there isn't a free connection available in the pool. You can useDB.SetMaxOpenConnsto set the maximum size of the pool. Connections that are not being used are marked idle and then closed if they aren't required. To avoid making and closing lots of connections, set the maximum idle size withDB.SetMaxIdleConnsto a size that is sensible for your query loads.It is easy to get into trouble by accidentally holding on to connections. To prevent this:Ensure youScan()every Row objectEnsure you eitherClose()or fully-iterate viaNext()every Rows objectEnsure every transaction returns its connection viaCommit()orRollback()If you neglect to do one of these things, the connections they use may be held until garbage collection, and your db will end up creating far more connections at once in order to compensate for the ones its using. Note thatRows.Close()can be called multiple times safely, so do not fear calling it where it might not be necessary. $ gogetgithub.com/jmoiron/sqlx $ go get github . com / jmoiron / sqlx $ gogetgithub.com/mattn/go-sqlite3 $ go get github . com / mattn / go - sqlite3 vardb*sqlx.DB var db * sqlx . DB // exactly the same as the built-in // exactly the same as the built-in db=sqlx.Open(\"sqlite3\",\":memory:\") db = sqlx . Open ( \"sqlite3\" , \":memory:\" ) // from a pre-existing sql.DB; note",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "f183f8a0-494a-41e9-8763-186bafa032c0"
},
{
"text": "the required driverName // from a pre-existing sql.DB; note the required driverName db=sqlx.NewDb(sql.Open(\"sqlite3\",\":memory:\"),\"sqlite3\") db = sqlx . NewDb ( sql . Open ( \"sqlite3\" , \":memory:\" ), \"sqlite3\" ) // force a connection and test that it worked // force a connection and test that it worked err=db.Ping() err = db . Ping () varerr error var err error // open and connect at the same time: // open and connect at the same time: db,err=sqlx.Connect(\"sqlite3\",\":memory:\") db , err = sqlx . Connect ( \"sqlite3\" , \":memory:\" ) // open and connect at the same time, panicing on error // open and connect at the same time, panicing on error db=sqlx.MustConnect(\"sqlite3\",\":memory:\") db = sqlx . MustConnect ( \"sqlite3\" , \":memory:\" ) schema:=`CREATE TABLE place ( schema := `CREATE TABLE place ( country text, country text, city text NULL, city text NULL, telcode integer);` telcode integer);` // execute a query on the server // execute a query on the server result,err:=db.Exec(schema) result , err := db . Exec ( schema ) // or, you can use MustExec, which panics on error // or, you can use MustExec, which panics on error cityState:=`INSERT INTO place (country, telcode) VALUES (?, ?)` cityState := `INSERT INTO place (country, telcode) VALUES (?, ?)` countryCity:=`INSERT INTO place (country, city, telcode) VALUES (?, ?, ?)` countryCity := `INSERT INTO place (country, city, telcode) VALUES (?, ?, ?)` db.MustExec(cityState,\"Hong Kong\",852) db . MustExec ( cityState , \"Hong Kong\" , 852 ) db.MustExec(cityState,\"Singapore\",65) db . MustExec ( cityState , \"Singapore\" , 65 ) db.MustExec(countryCity,\"South Africa\",\"Johannesburg\",27) db . MustExec ( countryCity , \"South Africa\" , \"Johannesburg\" , 27 ) // doesn't work // doesn't work db.Query(\"SELECT * FROM ?\",\"mytable\") db . Query ( \"SELECT * FROM ?\" , \"mytable\" ) // also doesn't work // also doesn't work db.Query(\"SELECT ?, ? FROM people\",\"name\",\"location\") db . Query ( \"SELECT ?, ? FROM people\" , \"name\" , \"location\" ) // fetch all places from the db // fetch all places from the db rows,err:=db.Query(\"SELECT country, city, telcode FROM place\") rows , err := db . Query ( \"SELECT country, city, telcode FROM place\" ) // iterate over each row // iterate over each row forrows.Next(){ for rows . Next () { varcountrystring var country string // note that city can be NULL, so we use the NullString type // note that city can be NULL, so we use the NullString type varcity sql.NullString var city sql . NullString vartelcodeint var telcode int err=rows.Scan(&country,&city,&telcode) err = rows . Scan (& country , & city , & telcode ) } } // check the error from rows // check the error from rows err=rows.Err() err = rows . Err () typePlacestruct{ type Place struct { Countrystring Country string Citysql.NullString City sql . NullString TelephoneCodeint`db:\"telcode\"` TelephoneCode int `db:\"telcode\"` } } rows,err:=db.Queryx(\"SELECT * FROM place\") rows , err := db . Queryx ( \"SELECT * FROM place\" ) forrows.Next(){ for rows . Next () { varpPlace var p Place err=rows.StructScan(&p) err = rows . StructScan (&",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "070f083f-51cf-4488-bda8-fa779f3fb470"
},
{
"text": "p ) } } row:=db.QueryRow(\"SELECT * FROM place WHERE telcode=?\",852) row := db . QueryRow ( \"SELECT * FROM place WHERE telcode=?\" , 852 ) vartelcodeint var telcode int err=row.Scan(&telcode) err = row . Scan (& telcode ) varpPlace var p Place err:=db.QueryRowx(\"SELECT city, telcode FROM place LIMIT 1\").StructScan(&p) err := db . QueryRowx ( \"SELECT city, telcode FROM place LIMIT 1\" ). StructScan (& p ) p:=Place{} p := Place {} pp:=[]Place{} pp := [] Place {} // this will pull the first place directly into p // this will pull the first place directly into p err=db.Get(&p,\"SELECT * FROM place LIMIT 1\") err = db . Get (& p , \"SELECT * FROM place LIMIT 1\" ) // this will pull places with telcode > 50 into the slice pp // this will pull places with telcode > 50 into the slice pp err=db.Select(&pp,\"SELECT * FROM place WHERE telcode > ?\",50) err = db . Select (& pp , \"SELECT * FROM place WHERE telcode > ?\" , 50 ) // they work with regular types as well // they work with regular types as well varidint var id int err=db.Get(&id,\"SELECT count(*) FROM place\") err = db . Get (& id , \"SELECT count(*) FROM place\" ) // fetch at most 10 place names // fetch at most 10 place names varnames[]string var names [] string err=db.Select(&names,\"SELECT name FROM place LIMIT 10\") err = db . Select (& names , \"SELECT name FROM place LIMIT 10\" ) // this will not work if connection pool > 1 // this will not work if connection pool > 1 db.MustExec(\"BEGIN;\") db . MustExec ( \"BEGIN;\" ) db.MustExec(...) db . MustExec (...) db.MustExec(\"COMMIT;\") db . MustExec ( \"COMMIT;\" ) tx,err:=db.Begin() tx , err := db . Begin () err=tx.Exec(...) err = tx . Exec (...) err=tx.Commit() err = tx . Commit () tx:=db.MustBegin() tx := db . MustBegin () tx.MustExec(...) tx . MustExec (...) err=tx.Commit() err = tx . Commit () stmt,err:=db.Prepare(`SELECT * FROM place WHERE telcode=?`) stmt , err := db . Prepare ( `SELECT * FROM place WHERE telcode=?` ) row=stmt.QueryRow(65) row = stmt . QueryRow ( 65 ) tx,err:=db.Begin() tx , err := db . Begin () txStmt,err:=tx.Prepare(`SELECT * FROM place WHERE telcode=?`) txStmt , err := tx . Prepare ( `SELECT * FROM place WHERE telcode=?` ) row=txStmt.QueryRow(852) row = txStmt . QueryRow ( 852 ) stmt,err:=db.Preparex(`SELECT * FROM place WHERE telcode=?`) stmt , err := db . Preparex ( `SELECT * FROM place WHERE telcode=?` ) varpPlace var p Place err=stmt.Get(&p,852) err = stmt . Get (& p , 852 ) SELECT*FROM users WHERE level IN(?); SELECT * FROM users WHERE level IN (?); varlevels=[]int{4,6,7} var levels = [] int { 4 , 6 , 7 } rows,err:=db.Query(\"SELECT * FROM users WHERE level IN (?);\",levels) rows , err := db . Query ( \"SELECT * FROM users WHERE level IN (?);\" , levels ) varlevels=[]int{4,6,7} var levels = [] int { 4 , 6 , 7",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "0dd583a4-110f-4de4-9ea3-1ceda5a360d7"
},
{
"text": "} query,args,err:=sqlx.In(\"SELECT * FROM users WHERE level IN (?);\",levels) query , args , err := sqlx . In ( \"SELECT * FROM users WHERE level IN (?);\" , levels ) // sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend // sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend query=db.Rebind(query) query = db . Rebind ( query ) rows,err:=db.Query(query,args...) rows , err := db . Query ( query , args ...) // named query with a struct // named query with a struct p:=Place{Country:\"South Africa\"} p := Place { Country : \"South Africa\" } rows,err:=db.NamedQuery(`SELECT * FROM place WHERE country=:country`,p) rows , err := db . NamedQuery ( `SELECT * FROM place WHERE country=:country` , p ) // named query with a map // named query with a map m:=map[string]interface{}{\"city\":\"Johannesburg\"} m := map [ string ] interface {}{ \"city\" : \"Johannesburg\" } result,err:=db.NamedExec(`SELECT * FROM place WHERE city=:city`,m) result , err := db . NamedExec ( `SELECT * FROM place WHERE city=:city` , m ) p:=Place{TelephoneCode:50} p := Place { TelephoneCode : 50 } pp:=[]Place{} pp := [] Place {} // select all telcodes > 50 // select all telcodes > 50 nstmt,err:=db.PrepareNamed(`SELECT * FROM place WHERE telcode > :telcode`) nstmt , err := db . PrepareNamed ( `SELECT * FROM place WHERE telcode > :telcode` ) err=nstmt.Select(&pp,p) err = nstmt . Select (& pp , p ) arg:=map[string]interface{}{ arg := map [ string ] interface {}{ \"published\":true, \"published\" : true , \"authors\":[]{8,19,32,44}, \"authors\" : []{ 8 , 19 , 32 , 44 }, } } query,args,err:=sqlx.Named(\"SELECT * FROM articles WHERE published=:published AND author_id IN (:authors)\",arg) query , args , err := sqlx . Named ( \"SELECT * FROM articles WHERE published=:published AND author_id IN (:authors)\" , arg ) query,args,err:=sqlx.In(query,args...) query , args , err := sqlx . In ( query , args ...) query=db.Rebind(query) query = db . Rebind ( query ) db.Query(query,args...) db . Query ( query , args ...) typeAutoIncrstruct{ type AutoIncr struct { ID uint64 ID uint64 Createdtime.Time Created time . Time } } typePlacestruct{ type Place struct { Addressstring Address string AutoIncr AutoIncr } } typePersonstruct{ type Person struct { Namestring Name string AutoIncr AutoIncr } } typeEmployeestruct{ type Employee struct { BossIDuint64 BossID uint64 EmployeeIDuint64 EmployeeID uint64 Person Person } } typeChildstruct{ type Child struct { FatherPerson Father Person MotherPerson Mother Person } } typePersonPlacestruct{ type PersonPlace struct { Person Person Place Place } } varpPerson var p Person // err here is not nil because there are no field destinations for columns in `place` // err here is not nil because there are no field destinations for columns in `place` err=db.Get(&p,\"SELECT * FROM person, place LIMIT 1;\") err = db . Get (& p , \"SELECT * FROM person, place LIMIT 1;\" ) // this will NOT return an error, even though place columns have no destination // this will NOT return an error, even though place columns have no destination udb:=db.Unsafe()",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "f9af5f8c-59ca-4906-9e26-2b8194e4d2f6"
},
{
"text": "udb := db . Unsafe () err=udb.Get(&p,\"SELECT * FROM person, place LIMIT 1;\") err = udb . Get (& p , \"SELECT * FROM person, place LIMIT 1;\" ) // if our db schema uses ALLCAPS columns, we can use normal fields // if our db schema uses ALLCAPS columns, we can use normal fields db.MapperFunc(strings.ToUpper) db . MapperFunc ( strings . ToUpper ) // suppose a library uses lowercase columns, we can create a copy // suppose a library uses lowercase columns, we can create a copy copy:=sqlx.NewDb(db.DB,db.DriverName()) copy := sqlx . NewDb ( db . DB , db . DriverName ()) copy.MapperFunc(strings.ToLower) copy . MapperFunc ( strings . ToLower ) import\"github.com/jmoiron/sqlx/reflectx\" import \"github.com/jmoiron/sqlx/reflectx\" // Create a new mapper which will use the struct field tag \"json\" instead of \"db\" // Create a new mapper which will use the struct field tag \"json\" instead of \"db\" db.Mapper=reflectx.NewMapperFunc(\"json\",strings.ToLower) db . Mapper = reflectx . NewMapperFunc ( \"json\" , strings . ToLower ) rows,err:=db.Queryx(\"SELECT * FROM place\") rows , err := db . Queryx ( \"SELECT * FROM place\" ) forrows.Next(){ for rows . Next () { // cols is an []interface{} of all of the column results // cols is an []interface{} of all of the column results cols,err:=rows.SliceScan() cols , err := rows . SliceScan () } } rows,err:=db.Queryx(\"SELECT * FROM place\") rows , err := db . Queryx ( \"SELECT * FROM place\" ) forrows.Next(){ for rows . Next () { results:=make(map[string]interface{}) results := make ( map [ string ] interface {}) err=rows.MapScan(results) err = rows . MapScan ( results ) } }",
"source": "https://jmoiron.github.io/sqlx/",
"type": "web",
"timestamp": "9690e3c2-9299-4d33-b26b-0a26307d2c79"
}
]