mug / mug-safesql
AGENTS.md540 starsChanged 12 days agoApache-2.0View on GitHub
When generating or refactoring code using SafeSql.java, follow these rules to ensure safety against SQL injection and maintain readability. 1. Placeholder Syntax: {placeholder} is the syntax to interpolate into the query template, using the SafeSql.of() static factory method. 2. Supported Types: Primitive type numbers, strings, java.time.Instant, java.time.LocalDate, java.time.ZonedDateTime, and List thereof. 3. String Values Should Be Quoted: String placeholders intended to be values should be quoted by single quotes like '{user_id}'. While not strictly required, it makes the intent more…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,266 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository3 other files it gives its agents.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
22 rules. About 0 are common, 8 are distinctive, and 14 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈8
Distinctive · estimate
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 5
When generating or refactoring code using SafeSql.java, follow these rules to ensure safety against SQL injection and maintain readability.
- Distinctive: line 22
All compositions are done through templating.
- Very specific: line 33
Values (Numbers or general): Leave the placeholder unquoted (e.g., IN ({ids})) to expand a list of values (like integers) into parameters.
- Distinctive: line 49
Conditional Clause: Use conditional placeholders to include snippets based on a boolean.
- Distinctive: line 57
Optional and Nullable Parameters: Use conditional placeholders with optional or nullable values.
- Distinctive: line 82
Placeholder Name Reuse: If the query expects to use the same identifier or same value at multiple places, make sure to use the same …
- Very specific: line 86
LIKE Clauses and Wildcards: When using the LIKE operator, use the syntax LIKE '%{placeholder}%' (or '%{placeholder}', '{placeholder}%').
- Very specific: line 104
Only %, _ and ^ are escaped.
- Very specific: line 119
SafeSql.when(boolean, String, Object...): Use this method when an entire query snippet should be guarded on a condition. - Very specific: line 159
Prefer Text Blocks: Prefer using triple-quote """ text blocks over string concatenation for multi-line queries.
- Distinctive: line 162
No Loops or If-Else in Templates: No loops or if-else statements are supported in the minimalist templating.
- Distinctive: line 195
Consistent Naming: Prefer to name placeholders and variables or methods consistently so they naturally match the template placeholder …
- Very specific: line 199
Explicit Comments: If you must force a match, you can use an explicit comment like /* placeholder_name */ in front of the value.
- Distinctive: line 203
Formatting: When using explicit comments to force matching, properly format the placeholder values one per line, as the Google Java …
- Very specific: line 207
Avoid Over-Commenting: Don't blindly comment for every argument when they already match naturally (e.g., /* user_id */ user.id() is silly).
- Distinctive: line 209
Trailing Comments: When passing one placeholder parameter per line, and you need to use a comment, use the trailing style:
- Very specific: line 235
SQL Injection Prevention: All placeholders, unless double-or-backtick quoted, or is itself a SafeSql, will have their values passed as …
- Very specific: line 262
If you are using Spring's JdbcTemplate, you can integrate it by using toString() to get the parameterized SQL string and args() to get the …
- Very specific: line 300
Executing Updates: Use update to execute INSERT, UPDATE, or DELETE statements.
- Very specific: line 309
Lazy Streaming: Use queryLazily to stream results.
- Very specific: line 375
All Construction via Templating: All query construction must be done through string templates using SafeSql.of(), SafeSql.when(), and …
- Very specific: line 379
Do Not Guess Methods: Do not assume methods exist for dynamically building queries.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Rules for AI Agents Generating Code
SafeSql.java
When generating or refactoring code using SafeSql.java, follow these rules
to ensure safety against SQL injection and maintain readability.
1. Templating Rules
- Placeholder Syntax:
{placeholder}is the syntax to interpolate into the query template, using theSafeSql.of()static factory method. - Supported Types: Primitive type numbers, strings,
java.time.Instant,java.time.LocalDate,java.time.ZonedDateTime, andListthereof. - String Values Should Be Quoted: String placeholders intended to be
values should be quoted by single quotes like
'{user_id}'. While not strictly required, it makes the intent more explicit to the code readers. - Identifiers Must Be Quoted by Double Quotes: String placeholders intended to be identifiers should be quoted by double quotes (or backticks). They will be sanity checked to ensure no dangerous characters are used.
- Query Composition:
SafeSqlitself can be passed as placeholder values. This allows arbitrarily complex and dynamic query composition. All compositions are done through templating. - Raw SQL and Symbols: Parameters, except if the placeholder is
double-or-backtick quoted as identifier, are by default passed as
PreparedStatementparameters. If you must pass a trusted raw string or subquery, it must be anotherSafeSql. List Expansion:
- Identifiers: Double-quote the placeholder (e.g.,
"{columns}") to expand a list of identifiers. - Values (Strings in IN clause): You can single-quote the placeholder
inside an
INclause (e.g.,IN ('{names}')) for a list of strings. - Values (Numbers or general): Leave the placeholder unquoted (e.g.,
IN ({ids})) to expand a list of values (like integers) into parameters.
Examples:
// Expanding identifiers SafeSql query = SafeSql.of("SELECT \"{columns}\" FROM Users", asList("id", "name")); // Expands to: SELECT `id`, `name` FROM Users // Expanding values (unquoted) SafeSql query = SafeSql.of("SELECT * FROM Users WHERE id IN ({ids})", asList(1, 2, 3)); // Expands to: SELECT * FROM Users WHERE id IN (?, ?, ?)- Identifiers: Double-quote the placeholder (e.g.,
Conditional Clause: Use conditional placeholders to include snippets based on a boolean.
SafeSql.of("select {shows_id? -> id,} name from Users", showsId())This will include the
"id,"only ifshowsId()is true.Optional and Nullable Parameters: Use conditional placeholders with optional or nullable values.
SafeSql.of("select .. where {id? -> id = 'id?'}", id())This will generate
"where id = 'foo'"ifid()returnsOptional.of("foo")or simply"foo". It will omit the snippet ifid()returnsOptional.empty()or isnull. Null values are treated the same asOptional.empty(), allowing you to use nullable variables directly in conditional placeholders without wrapping them inOptional.Collection Parameters in Conditionals: Collection parameters can also be used in conditional queries.
SafeSql.of("... WHERE {ids? -> id IN ('ids?')}", ids())This will generate
"id in ('a', 'b')"ifids()returns[a, b], but ifids()returns[], it will be omitted.- Positional Parameters: The placeholder values are passed in positionally
like
String.format(). Their correctness will be checked such that the placeholder value expression must contain all the words in the placeholder name as a subset (in the same order), exceptget/isprefixes. - Placeholder Name Reuse: If the query expects to use the same identifier or same value at multiple places, make sure to use the same placeholder name. Then the compiler will ensure the same expression is passed for these placeholders.
LIKE Clauses and Wildcards: When using the
LIKEoperator, use the syntaxLIKE '%{placeholder}%'(or'%{placeholder}','{placeholder}%'). The query goes throughPreparedStatementparameterization (using?), so no SQL injection is possible. The library automatically handles wildcards by prefixing%,_, and^in the parameter value with^, and appendsESCAPE '^'to the generated SQL. Do not manually append theESCAPEclause.ILIKE(PostgreSQL, H2, CockroachDB) is recognized the same way asLIKE.Escaping is triggered by the wildcards in the template, not by the operator. A placeholder written alone (
LIKE '{placeholder}') is left unescaped and noESCAPEclause is added, because the parameter value is then the pattern rather than a literal fragment of it. Use that form only when the application deliberately supplies its own wildcards; prefer'%{placeholder}%'for user-supplied search terms.Only
%,_and^are escaped. SQL Server's[character-class wildcard is not escaped. On SQL Server, build the full pattern outside the template and pass it via the bareLIKE '{pattern}'form with your ownESCAPEclause.Example:
SafeSql query = SafeSql.of("SELECT * FROM Users WHERE name LIKE '%{name}%'", name); // Generated SQL: SELECT * FROM Users WHERE name LIKE ? ESCAPE '^'
2. Conditional Snippets
SafeSql.when(boolean, String, Object...): Use this method when an entire query snippet should be guarded on a condition.- It can be chained with
.orElse(String, Object...)or.orElse(SafeSql). Example:
SafeSql.when(useId(), "where id = '{id}'", id) .orElse("where id is null")- Both
when()andorElse()support the exact same template interpolation syntax asSafeSql.of(). Instance
when(boolean): Alternatively, if you already have aSafeSqlinstance, you can use the instance method.when(boolean)to conditionally include it. It returns the instance if true, orSafeSql.EMPTYif false. This allows for fluent chaining:SafeSql query = SafeSql.of( "SELECT * FROM Users {where}", SafeSql.of("WHERE id = {id}", userId).when(condition));
3. Subquery Joiners
SafeSql.and()andSafeSql.or(): These areCollectors used to combine a stream of subqueries usingANDandORoperators (e.g.,subqueries.stream().collect(SafeSql.and())). Proper parentheses are automatically added to preventAND/ORprecedence from changing the meaning of the query.SafeSql.joining(String delimiter): This is also aCollectorfor other types of subquery joins with a custom delimiter (e.g.,subqueries.stream().collect(SafeSql.joining(", "))).
4. Best Practices
- Prefer Text Blocks: Prefer using triple-quote
"""text blocks over string concatenation for multi-line queries. No Loops or If-Else in Templates: No loops or if-else statements are supported in the minimalist templating. The idea is to always do "logic" in Java and avoid template spaghetti. However, if you have two snippets that you want to use either one or the other depending on a boolean
fooEnabled(), you can use:SafeSql.of( """ ... {foo_enabled? -> foo,} {foo_disabled? -> cast(null as string) as foo,} ... """, fooEnabled(), fooDisabled()); // Helper methods in Java boolean fooEnabled(); boolean fooDisabled() { return !fooEnabled(); }- Line Wrapping in Conditionals: Newlines are supported to the right of
the arrow operator (
->) in conditional clauses. Use line wrapping properly to help readability of long conditional snippets. Naming Convention and Placeholder Matching: By default, the placeholder's expression must contain as a subset the words in the placeholder name. This acts as a safety net against mis-ordering varargs.
- Consistent Naming: Prefer to name placeholders and variables or methods consistently so they naturally match the template placeholder without extra work.
- Explicit Comments: If you must force a match, you can use an
explicit comment like
/* placeholder_name */in front of the value. This also tells code readers that you know what you are doing. - Formatting: When using explicit comments to force matching, properly format the placeholder values one per line, as the Google Java Formatter may otherwise format them poorly.
- Avoid Over-Commenting: Don't blindly comment for every argument when
they already match naturally (e.g.,
/* user_id */ user.id()is silly). Trailing Comments: When passing one placeholder parameter per line, and you need to use a comment, use the trailing style:
SafeSql.of( """ ... """, 1, // id 100); // size
5. Guardrails
- ErrorProne Recommendation: While not strictly required, it's strongly
recommended to use
SafeSqlwith ErrorProne in theannotationProcessorPaths. This helps to guard against SQL injection and ensures the semantic correctness of template parameters at compile time. - Compilation Errors: Compilation errors will point to the offending template argument when the naming convention or type check fails.
- Line Numbers in Templates: The error message will also show the line number of the corresponding placeholder in the template, making it easy to locate the issue in long queries.
- SQL Injection Prevention: All placeholders, unless double-or-backtick
quoted, or is itself a
SafeSql, will have their values passed asPreparedStatementparameters to avoid SQL injection. Identifier placeholders quoted by double quote or backtick will have the identifier string sanity checked to ensure there are no dangerous characters that can cause injection. - No Nesting in Conditionals: Within a conditional clause
{placeholder? -> ...}, do NOT use curly braces again for the placeholder expansion on the right side of the arrow. There is only one set of curly braces, which encloses the entire placeholder. Useplaceholder?directly (e.g.,{ids? -> id in ('ids?')}). Nesting curly braces will cause parsing errors. - Quoting Strings and Lists: Always use single or double quotes
(e.g.,
'{user_id}') for string values and double quotes (e.g.,"{column}") for string identifiers or lists of strings. Forgetting these quotes is a common mistake and will be caught as a compilation error to prevent SQL injection.
6. Execution and Integration
While SafeSql is primarily focused on safe query construction, it also
provides a simple API for execution and integration with other frameworks.
1. Spring JdbcTemplate Integration
If you are using Spring's JdbcTemplate, you can integrate it by using
toString() to get the parameterized SQL string and args() to get the
parameters:
SafeSql sql = SafeSql.of("SELECT * FROM Users WHERE id = {id}", userId);
List<User> users = jdbcTemplate.query(sql.toString(), sql.args(), rowMapper);2. Direct Execution (via DataSource)
SafeSql provides convenience methods to execute queries directly if you have a
DataSource. It is recommended to use these overloads to avoid manual resource
management.
Querying for Lists:
// Map to a Record or Java Bean SafeSql query = SafeSql.of("SELECT * FROM Users"); List<User> users = query.query(dataSource, User.class); // Map using a lambda function query = SafeSql.of("SELECT name FROM Users"); List<String> names = query.query(dataSource, row -> row.getString("name")); // Single column query (e.g., getting a list of IDs) query = SafeSql.of("SELECT id FROM Users"); List<Long> ids = query.query(dataSource, Long.class);Querying for Single Result:
SafeSql query = SafeSql.of("SELECT * FROM Users WHERE id = {id}", userId); Optional<User> user = query.queryForOne(dataSource, User.class);Executing Updates: Use
updateto executeINSERT,UPDATE, orDELETEstatements. It returns the number of affected rows.SafeSql query = SafeSql.of("UPDATE Users SET status = 'ACTIVE' WHERE id = {id}", userId); int rowsUpdated = query.update(dataSource);Lazy Streaming: Use
queryLazilyto stream results. Must be used within a try-with-resources block to ensure the connection is closed.SafeSql query = SafeSql.of("SELECT * FROM Users"); try (Stream<User> users = query.queryLazily(dataSource, User.class)) { users.forEach(System.out::println); } // Or for a single column query = SafeSql.of("SELECT id FROM Users"); try (Stream<Long> ids = query.queryLazily(dataSource, Long.class)) { ids.forEach(System.out::println); }
3. Customizing Statements
You can customize the Statement or PreparedStatement (e.g., to set fetch
size or max rows) by passing a StatementSettings lambda:
SafeSql query = SafeSql.of("SELECT * FROM Users");
List<User> users = query.query(
dataSource,
stmt -> stmt.setFetchSize(100),
User.class);4. Performance & Batching (via Connection)
For cases where you need to reuse statements or perform batch operations,
SafeSql provides APIs that take a Connection (instead of DataSource):
Reusable Templates:
try (Connection conn = dataSource.getConnection()) { var query = SafeSql.prepareToQuery( conn, "SELECT * FROM Users WHERE name = {name}", User.class); List<User> users1 = query.with("Alice"); List<User> users2 = query.with("Bob"); }Batching:
try (Connection conn = dataSource.getConnection()) { var insertUser = SafeSql.prepareToBatch( conn, "INSERT INTO Users(id, name) VALUES({id}, '{name}')"); Set<Statement> batches = users.stream() .map(user -> insertUser.with(user.id(), user.name())) .collect(toUnmodifiableSet()); for (Statement batch : batches) { batch.executeBatch(); } }
7. Avoiding API Hallucination
- No Fluent Builder Pattern:
SafeSqldoes not support a fluent builder pattern for SQL clauses. There are no methods likeselect(),from(),where(), ororderBy(). - All Construction via Templating: All query construction must be done
through string templates using
SafeSql.of(),SafeSql.when(), and composition by passingSafeSqlobjects as placeholder values. - Do Not Guess Methods: Do not assume methods exist for dynamically
building queries. If it's not in the small set of methods documented above
(
of,when,orElse,and,or,joining), it does not exist.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

