Changelog
3.6.0
What's new
- The graph options of
insertGraph()/upsertGraph()that take relation paths (relate,unrelate,insertMissing,update,noInsert,noUpdate,noDelete,noRelate,noUnrelate) also accept a relation expression in the same syntax aswithGraphFetched(), e.g.noInsert: '*'ornoDelete: '[pets, movies.reviews]'. Like the array, an expression only matches the relations at the end of the paths it names, so'movies.reviews'doesn't matchmovies.'*'matches all relations at any depth, and recursive expressions like'parent.^'every level of the recursion. Root models are never matched, sonoInsert: '*'inserts new root models but no related ones. Aliases and empty expressions throw an error. #131
Fixes
upsertGraph()patches the related models of many-to-many relations by their id, and their extra properties in the join row by the ids of both ends. Until now these patches filtered by a subquery that joins the join table, and on MySQL, the patches of a graph upserted without a transaction deadlocked each other. The SQL of these patches changes. #135- The warning from 3.4.0 about owner models missing a join property skips the foreign key of a
BelongsToOneRelation, unless it's part of the id. It's also missing when it was never set, e.g. on models returned byinsert()or created withfromJson(), where no related model is the right result. A foreign key left out of a partialselect()looks the same and no longer warns either. Join properties of all other relations still warn, including non-id columns. #132 relate(),$relatedQuery().insert()andinsertGraph()/upsertGraph()inserting or relating models of many-to-many and has-one-through relations whose join table is also the related table throw an error, likeunrelate()since 3.4.0. They inserted the join rows as new related rows, or failed with unique violations after inserting the related rows. #133- Recursive upserts of related models with children no longer warn about the unknown graph option
optionssince 3.4.0
Other
- Replace the custom build of lodash's
cloneDeep()from 2018 with a small implementation, which$clone(),toJSON()and validation use to copy objects in model properties. It copies model data the same way, 2 to 4 times faster. Objects with anullprototype keep it instead of gettingObject.prototype, andBigInt64Array/BigUint64Arrayare copied instead of shared. - The parsers of relation expressions and JSON field expressions are generated with Peggy instead of PEG.js 0.10, with
npm run build:parsers. Parse results and error messages are the same. - The example projects use current versions of their dependencies and need Node.js 20.17 or newer
3.5.0
What's new
- Add the
mapNestedKeysoption toknexSnakeCaseMappers()andknexIdentifierMapping(), which also converts the keys of objects nested one level down, e.g. the column names in the rows of knex'snestTables: trueoption on MySQL:knexSnakeCaseMappers({ mapNestedKeys: true })#2273 - The relation mapping's
beforeInsert(model, context, owner)hook receives the owner model as a third argument. WithinsertGraph()/upsertGraph()it's the parent object from the input graph, which may not be inserted yet, and it'sundefinedwhen the query was started from ids or several owners. #2240
Types
- Add the opt-in
TypedRelationMappings<M>helper: used withsatisfiesonrelationMappings, it checks that the mappings use relation properties of the model, a relation type matching their cardinality, and the rightmodelClass#16 - Add
Generated<T>to mark columns the database fills in, e.g.id!: Generated<number>, and theInsertable<M>/InsertableGraph<M>types for insert data, which leave them optional #16 - Add
isOneToOne()to theRelationtypings and docs. It's the safe way to check for relations to a single model, asHasOneRelationandHasOneThroughRelationextend the many-relations.
3.4.1
Fixes
- Select aliased aggregates like
count('* as n'),count('id', { as: 'n' })andcount({ n: 'id' })inwithGraphJoined()modifiers. They were treated as selecting all columns, or were missing from the result. Unaliased aggregates are left out, since their column name differs between databases. #2219 - JSON field expressions (
ref('col:path'),'col:path'keys in patches) and thewhereJson*()methods warn once on databases other than Postgres, where they generate invalid or silently wrong SQL. MySQL, for example, reads#>as a comment. On MySQL,whereJsonSupersetOf(column, value)/whereJsonSubsetOf(column, value)with a plain column and a JSON object or array are passed on to knex, which supports them there. #276 - Fix the infinite recursion in
andWhereJsonNotSupersetOf() - The warnings about missing join properties from 3.4.0 also cover
ManyToManyRelationandHasOneThroughRelation: owner models missing a join property, and related models that come back without the owner join column, e.g. stripped by$parseDatabaseJson(). #1832, #2258 - Warn once when a relation's owner join property holds an array, e.g. a JSON array of keys, which isn't supported and silently fetched no related models. Use a
ManyToManyRelationthrough a join table instead. #2667
3.4.0
What's new
- Support models without a primary key: return
nullfromidColumn, e.g. for join table models. Methods that need an identifier, likefindById(),deleteById()and$query(), throw an error. #2305
Fixes
insertGraph()/upsertGraph()withrelate: truesilently droppedHasManyRelation/HasOneRelationchildren whose composite id contains the foreign key, and deleted the existing ones without inserting them again #2544- Required properties given as query properties, e.g.
raw(),val(),ref()or subqueries, failed validation #2199 upsertGraph()treated JSON arrays and objects as unchanged when they loosely equal the current value, e.g.falseand[]#1874- Many-to-many and has-one-through relations whose join table is also the related table failed with SQL errors in
withGraphFetched(),$relatedQuery()andrelatedQuery().unrelate()and patching join table extras on such relations throw an error instead of modifying the wrong rows. #1803 - Patch validation rejected valid patches when an
anyOf/oneOfoption only consisted ofrequired#1681 - Throw
UniqueViolationErrorfor primary key violations on MSSQL #2688 $fetchGraph()/fetchGraph()/$relatedQuery()warn once when owner models are missing a join property, e.g. a foreign key left out of a partialselect(). The relation silently came back empty. #1832withGraphJoined()checks column aliases against the identifier length limit of the database (MySQL 256, MSSQL 128, SQLite none) instead of always the 63 of Postgres #2242withGraphFetched()/$fetchGraph()warn once when related models are missing a join property, e.g. snake_case relation mappings withknexSnakeCaseMappers(). They were silently dropped. #2258insertGraph()/upsertGraph()warn once per unknown option, e.g. a misspellednoInset. The option is ignored, and will throw in 4.0. #84
Types
- Add the
onlyoption tofrom(),table()andinto(), e.g. for PostgresONLY#2182
Docs
first()doesn't limit the related items per parent inmodifyGraph()#1647runAfter()in the queries of fetched relations can't replace the related models #2647page()andrange()need anorderBy()with a unique tiebreaker to avoid repeated or skipped rows #2575- Typing model properties with a merged interface #2237
- The
throughmapping of relations whose join table is also the related table #1803
Other
- Breaking for old knex: the knex peer dependency is
>=2.3.0instead of>=1.0.1. Some fixes of 3.3.0 don't work with older knex versions. CI now also tests knex 2.3.0. #95 - Tests no longer use bluebird, lodash and uuid
3.3.0
Security
- Escape keys in JSON field expressions. A
'in a key used inref(), a patch or update with field expression keys, or thewhereJson*methods broke out of the SQL string literal, allowing SQL injection when keys come from user input. #2077
What's new
withGraphFetched()/withGraphJoined()narrow the result types: fetched relations become required on the result. Generic helpers with an explicitQBreturn type needwithGraphFetched<string>(). #25- Add
withGraph()with algorithm-agnostic merging, andisJoinChildQuery()#63 - Add
patchById()andupdateById()#1415 insertGraph()/upsertGraph()resolve cyclic#refdependencies by deferringBelongsToOneforeign keys #1482- Add a
preserveJsonKeysoption tosnakeCaseMappers()to map only the column part of field expressions #1089 - Support empty keys in JSON field expressions, e.g.
col:[""]#2680. Behaviour change:col:[""]andcol:['']used to refer to a key consisting of the two quote characters. whereJson*methods acceptref(),val(),raw()and subqueries on the right side- Pass
returning()options, e.g.includeTriggerModifications, on to knex #2309
Fixes
- Group the user's where clauses when adding a relation's owner condition.
$relatedQuery(...).where(a).orWhere(b).delete()/patch()affected other owners' rows, and finds returned them. #2191, #1909 findByIds([])/whereInComposite()with an empty array and composite ids produced invalid SQL, and matched every row on SQLite #1914onConflict().ignore(): inserted rows were assigned to the wrong models,$setDatabaseJsoncould crash, andinsertAndFetch()fetched undefined ids #2320, #2597, #2661asFindQuery()in many-to-many update and delete hooks lost its filters #2266- Patch validation:
notschemas stay intact #1681, and nestedrequiredis stripped for nullable and untyped objects #1664 resultSize()andpage()count root models withwithGraphJoined()#2329, #2143- Keep aliased subquery and raw selections in
withGraphJoined()modifiers #2365 - Map column names in
whereJson*methods withknexSnakeCaseMappers - Match
table.*selections through knex identifier mapping #2288 - Use the keys of modified
graphExpressionObject()results #2793 - Track internally selected columns on the query builder, so
runAfter()hooks never see them #45 - Behaviour change: many-to-many
unrelate()/patch()only modify the join rows matching the filters, not all join rows of the matching related rows #1853. The generated SQL of these operations changes. On MySQL, the join table filter avoidsER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG#2127, andunrelate()returns0instead of[]when nothing matches. Ported from #2406. - Behaviour change:
asFindQuery()in hooks no longer applies therunAfter()callbacks of the original query, including those ofthrowIfNotFound()andtraverse(), and returns[]instead of[undefined]for afindById()that finds nothing #2093 - Behaviour change: field expression keys in patch objects, e.g.
'meta:a.b', are validated against the nested schema, so patches that passed before can fail validation #1666 - Behaviour change: the
joinOperationoption ofwithGraphJoined()applies per call, no longer to all relations of the query #2125 - Behaviour change:
withGraphJoined()throws when it can't identify rows, e.g. for a model without a primary key, instead of silently merging them #2748, #2737 insertGraph()/upsertGraph()warn whenonConflict(),ignore()ormerge()is used. The clause is ignored, and will throw in 4.0. #2156
Types
- Export the db-errors classes as types #2499
Docs
- The docs moved to VitePress and are hosted at ditojs.github.io/objection
- Document
relatedFindQueryMutates/relatedInsertQueryMutates#2356 - Document running code after a transaction commits #2582
Other
- Update knex to 3.3 in development, which fixes inverted bindings in
delete()withjoinRelated()#2799
Thanks to @falkenhawk and Marcin L for the many-to-many work in #2406, @kapouer for #2680 and @cesumilo for #2625, which led to preserveJsonKeys.
3.2.0
Objection is now maintained at ditojs/objection.
What's new
- Support mixing
withGraphJoined()andwithGraphFetched()in the same query. Before, the last method called silently decided the algorithm for all relations. A top-level relation can only be loaded with one of them. #2269 - Add
none()to make a query match no rows #2184 upsertGraph(): mark individual related models with#unrelateor#delete#2410- Return rows from
relate()withreturning()#2044 - Apply
select()to the fetch query ofupdateAndFetch(),patchAndFetch()and theirByIdvariants #1938 - Add a
noDoubleUnderscoresoption to the snake case mappers #2805 - Pass
formatoptions fromtoJSON()/$toJson()to$formatJson()of the model and all nested models #2033 - Support
$defsin JSON schemas #2576
Fixes
- Behaviour change: throw when
for()is used outside ofrelatedQuery(). It was silently ignored before, soModel.query().for(1).delete()deleted every row of the table. #2185 - Behaviour change: throw when
for()is called after a write method on arelatedQuery(). Before,update(),patch()anddelete()silently did nothing, andinsert()andrelate()wroteNULLforeign keys. - Fix validators being shared between models with the same
uniqueTag()but different schemas #2540 - Fix
orderBy()with refs and raws as array items #2252 - Clear an
orderByadded at build time, e.g. by a relation'smodify, from theresultSize()andpage()count query #2747 - Support
Model.ref()references in relation join mappings #1873 - Reference the bare column in JSON where methods when no JSON path is given, so Postgres can use GIN indexes #2008
- Fix subqueries in join builders on MySQL (
parentQuery.isUpdate is not a function) #2407 - Make
union()deduplicate regardless of array size #2811 - Serialize relation modifiers and aliases before the recursion marker in
RelationExpression.toString()#2812
Types
- Fix
first()infinite type recursion in custom query builder methods #2637 - Keep nested relation data type-checked when inserting model data interfaces #2190
- Keep custom query builder types after
throwIfNotFound() - Add a
QueryBuilderconstructor typing for custom query builders #2306 - Allow
nulland readonly arrays foridColumn, readonly arrays forjsonAttributes#2693, #2745 - Allow
bigintvalues in where methods #2318 - Support object joins,
limit()/offset()withskipBinding, and aliased aggregates #2189 - Fix
tableNameFor()andtableRefFor()return and argument types #2790 - Add
knexIdentifierMapping#1947 - Add
tableName(),tableRef()andemptyInstance()toQueryBuilder#2792, #2794 - Add the column list overload of
with()#2749 - Fix generic static
thisforquery(),fromJson()andfetchGraph()#2700
Docs
- Document what
afterInsert()receives asresult#2342 - Document that
withGraphJoined()requires a primary key #2748 - Document the
skipUndefined()deprecation #2149 - Use
declarefor the query builder type properties in the custom query builder and plugin recipes, which fail with TS2612 on ES2022+ targets - Fix the koa-ts example typings #2361
- Clarify
whereNotColumn()#2808
Other
- Drop Node 14 from CI. Objection still supports it, but knex 3 requires Node 16+.
Thanks to everyone whose pull requests made it into this release: @amit-meshbey, @androvonx95, @bilalakbar, @Bolt4243, @cesumilo, @falkenhawk, @geeksilva97, @IlyaSemenov, @kapouer, @kartikdp, @LiahMartens, @max-kahnt-keylight, @nickbouldien, @nickfuryoc, @ralcorta and @salisbury-espinosa.
3.1.5
What's new
- Types: Fix generic static
this#2533 - Types: Add
fromRawto `FromSelector regex #2628 - Types: Fix argument types of
onConflict()#2635 - Types: Make
trxoptional forModel.transaction(trx, cb)#2694
3.1.4
What's new
- Fix
upsertGraph()$beforeUpdate()calls on empty relates #2605 - Don't call
onError()with internal exceptions #2603 - Remove docs and typings for nonexistent
$pick() - Make
$omitFromJson()+$omitFromDatabaseJson()compatible with old$omit()syntax
3.1.3
What's new
What's new
- Patch Validator: Prevent recursion on inner properties #2520
3.1.2
What's new
- Patch Validator: Prevent recursion on inner properties #2520
3.1.1
What's new
- Only add Ajv formats if they weren't added in user-land already #2482
3.1.0
What's new
- Support
$beforeUpdate()mutations inupsertGraph()#2233 - Remove deprecated
$afterGet()hook #2477 - Drop support for Node v12 #2478
3.0.5
What's new
3.0.4
What's new
- Fixes #2447
3.0.3
What's new
- Fixes #1673
- Fixes #1957
- Fixes #2105
- Fixes #2132
- Fixes #2251
- Fixes #2262
- Fixes #2271
- Fixes #2277
- Fixes #2308
- Fixes #2311
- Fixes #2311
- Fixes #2311
- Fixes #2332
- Fixes #2337
- Fixes #2372
- Fixes #2379
- Fixes #2383
- Fixes #2399
- Fixes #2404
- Fixes #2405
- Fixes #2408
- Fixes #2409
- Fixes #2423
3.0.2
What's new
- Fixes #1356
- Fixes #1957
- Fixes #2192
- Fixes #2247
- Fixes #2307
- Fixes #2308
- Fixes #2311
- Fixes #2323
- Fixes #2337
- Fixes #2362
3.0.1
What's new
3.0.0
What's new
- Fixes #1986
- Fixes #1987
- Fixes #1954
- Fixes #1993
- Fixes #1688
- Fixes #1651
- Fixes #2135
- Fixes #1936
- Fixes #1905
- Fixes #1997
- Fixes #2024
Breaking changes
See the migration guide.
2.2.10
What's new
- Add
modelClassproperty forValidationErrorandNotFoundError.
2.2.9
What's new
- Add
noWaitquery builder method.
2.2.8
What's new
2.2.7
What's new
QueryBuilder.castTocan now be used to cast query results to any typescript type.
2.2.6
What's new
- Fixes #1964
2.2.5
What's new
- Fixes #1855
2.2.4
What's new
- Add support for onConflict, merge and ignore knex methods.
2.2.2
What's new
2.2.1
What's new
2.2.0
What's new
2.1.4
What's new
- Fixes #1750
2.1.3
What's new
- Add
underscoreBetweenUppercaseLettersoption for snake case mappers. #1676
2.1.2
What's new
- Fix
startTransactiontypings.
2.1.1
What's new
- Fixes #1489
2.1.0
What's new
Changelog
2.0.10
What's new
- Fixes #1630
2.0.9
What's new
- Fixes #1606
2.0.8
What's new
- Fixes #1627
2.0.7
What's new
- Fixes #1607
2.0.6
What's new
- Fixes #1603
2.0.5
What's new
- Fixes
upsertGraphbug where composite keys were not selected correctly. See the fix here.
2.0.4
What's new
- New
skipFetchedoption forfetchGraphand$fetchGraph
2.0.3
What's new
2.0.0
What's new
Cleaner and more consistent API. A lot of methods have been renamed, removed combined and cleaned up. Most of the old methods still exist, but print a deprecation warning when first used. Some examples:
eager->withGraphFetchedjoinEager->withGraphJoined- removed
eagerAlgorithm(you must explicitly use eitherwithGraphFetchedorwithGraphJoined) - merged
allowEager,allowInsertandallowUpsertinto one methodallowGraph $loadRelated->$fetchGraphjoinRelation->joinRelated$relatedQueryno longer mutates the receiving model instances
New static hook API. The old instance hooks are still around.
relatedQuerycan now be used for more than just subqueries. See the examples here.modifiers can now take arguments and are a lot more useful. See this recipe for more info.
Objection now uses the db-errors library by default to wrap the database errors.
insertMissingupsertGraphoption now works as expected withrelate: true: items that are not found in the database are inserted.Brand new typings written from scratch with many improvements and finally a support for custom query builders
A bunch of improvements and bug fixes for
upsertGraph, including a huge speedup in some cases due to less data fetching.A brand new fn helper for calling SQL functions.
Objection now uses native promises instead of bluebird.
Objection is now leaner as we dropped a bunch of dependencies like
bluebirdandlodash.In addition to all of this, a huge number of bugs has been squashed!
Breaking changes
See the migration guide.
1.6.10
- Fixes #1455
1.6.9
- Revert fix for #1089. It was causing more bugs than it fixed. #1089 will be addressed in 2.0.
- Typings updates
1.6.8
- Fix #1287
1.6.7
- A bunch of regression bug fixes.
1.6.3
- Fixes: #1227
1.6.2
- Add
asmethod forrawmaking it possible to userawexpressions injoinEagermodifiers (as long as you give names to your raw expressions usingas).
1.6.1
- Fix some very rare upsertGraph edge cases.
1.6.0
Add
Model.traverseAsyncandmodelInstance.$traverseAsyncmethods.Fixes: #842 and #1205. This bug is about subqueries "inheriting" parent query table name and alias. This bug has been around a long time and there is a small chance that people have started accidentally or on purpose use it as a feature. If you get weird reference errors from subqueries (relation not found, table not found etc.) you may need to explicitly give an alias or use
fromin your subqueries after this update. This is a borderline breaking change, but since 2.0 is still pretty far away, I wanted to get this out faster. If I'm wrong and people are heavily depending on this bug, I'll revert the change.Fixes: #1215
Fixes: #1206
1.5.3
What's new
- Fixes #1204
1.5.1
What's new
- Relations are now loaded lazily #1202
relationMappings.modelClasscan now be a function that returns a model class.
1.5.0
What's new
- fix #1131
- fix #1114
- fix #1185
- fix #1109
- fix #1110
- add eagerObject and eagerModifiers accessors to QueryBuilder.
- complete rewrite of
insertGraphandupsertGraphcode. The rewrite brought a bunch of small performance optimizations and makes future development easier. No breaking changes. - Chaining
returning('*')toinsertGraphorupsertGraphnow propagates the call to all insert, update and delete operations. - Code using objectio can now be transpilsed to ES5. No need to add babel workarounds anymore.
1.4.0
What's new
1.3.0
What's new
- Use
objection.rawinstead ofknex.rawinModel.raw. #1077 - Allow modifiers (namedFilters) to be used in
modifyEagertoo. - Add
underscoreBeforeDigitsoption for snake case converters. #1025 - fix #1074
- Typing fixes
1.2.3
What's new
1.2.2
What's new
- Improve reference cycle detection in
upsertGraph
1.2.1
What's new
- fix #1009
1.2.0
What's new
- fix #919
- fix #964
- Add
aliasFormethod to public API - Prevent bluebird warnings
- UPPER_SNAKE_CASE support for
snakeCaseMappersandknexSnakeCaseMappers
1.1.10
What's new
- Nothing! the npm release was somehow borked. This was just a rerelease of 1.1.9.
1.1.9
What's new
- fix #782
1.1.8
What's new
- fix #909
1.1.7
What's new
- fix #884
1.1.6
What's new
- Add typings for fetchTableMetadata, tableMetadata and onbuildknex
1.1.5
What's new
- Make Model.fetchTableMetadata and Model.tableMetadata methods public. #871
- Add onBuildKnex query builder hook. #807
1.1.4
What's new
- fix subquery bug causing incompatibility with knex 0.14.5 and sqlite3
1.1.3
What's new
- fix regression in 1.1.2 (sorry about this) #869
1.1.2
What's new
1.1.1
What's new
- fix #865
- fix bug where the static
Model.relatedQuerydidn't use the relation name as an alias for the table. This may break code if you have explicitly referenced the subquery table. #859
1.1.0
What's new
- Optional object notation for relation expressions.
- fix #855
- fix #858
1.0.1
What's new
- Added public Relation.joinModelClass accessor
- Don't call
returningon sqlite (prevents a warning message added in knex 0.14.4) - fix #844
- Small documentation updates
- Small typing fixes end updates
1.0.0 🎉
What's new
- The static
relatedQuerymethod. - New reflection methods:
isFind,isInsert,isUpdate,isDelete,isRelate,isUnrelate,hasWheres,hasSelects,hasEager,has.clear.columnNameToPropertyName,propertyNameToColumnName. ManyToManyextras now work consistently in queries and filters. #760
Breaking changes
modelInstance.$query().delete().returning(something)now returns a single instance instead of an array. #659Node 6.0.0 is now the minimum. Objection will not work on node < 6.0.0.
ValidationErroroverhaul. This is a big one, so read this carefully! There are three things to check when you migrate to 1.0:- The
createValidationErrorandValidationErrorinterfaces have changed. If you have overridden thecreateValidationErrormethod in your project, or you create customValidationErrorinstances you need migrate to the interfaces. - The model validation errors (jsonSchema violations) have remained pretty much the same but there are couple of differences. Before, the keys of
error.datawere property names even when a nested object in a graph failed a validation. Now the keys for nested validation errors are key paths likefoo.bar[2].spam. Another tiny difference is the order of validation errors for each key inerror.data. Let's say a propertyspamfailed for your model anderror.data.spamcontains an array of objects that describe the failures. Before, the first failed validation was the last item in the array, now it is the first item. - All
ValidationErrorsnow have atypefield. Before allValidationErrorsbut the model validation errors (errors like "invalid relation expression", or "cyclic model graph") had no type, and could only be identified based on the existence of some weird key inerror.data. Theerror.datais now removed from those errors and thetypeshould be used instead. The message from the data is now stored inerror.message.
- The
Removed deprecated methods
whereRef,whereJsonFieldandwhereJsonEquals. Therefhelper can be used to replace thewhereRefcalls.refandlitcan be used to replace the removed json methods.ManyToManyextras now work consistently in queries and filters. #760. This is not a breaking change per se, but can cause some queries to fail with a "ambiguous identifier" error because the join table is now joined in places where it previously wasn't. You need to explicitly specify the table for those failing columns usingTable.theColumnsyntax.
Changes
isFindQueryis renamed toisFindand deprecated.
0.9.4
What's new
0.9.3
What's new
- Add beforeInsert hook for relations. #649 #19
- Add
relatedFindQueryMutatesandrelatedInsertQueryMutatesconfigs as well as$setRelatedand$appendRelatedhelpers. #599 - Fixed #648
0.9.2
What's new
- Fix regression:
fromfails with a subquery.
0.9.1
What's new
castTomethod for setting the model class of query result rows.onErrorQueryBuildermethod.knexSnakeCaseMappersandsnakeCaseMappersfor snake_case to camelCase conversions.
0.9.0
What's new
- Relations can now be defined using keys inside JSON columns. See the examples here.
lithelper function #275- Fixes for
upsertGraphwhen using composite keys. #517 - Added
noDelete,noUpdate,noInsert,noRelateandnoUnrelateoptions forupsertGraph. See UpsertGraphOptions docs for more info. insertGraphnow accepts an options object just likeupsertGraph.relateoption can be used instead of#dbRef. #586
Breaking changes
Instance update/patch with
returningnow return a single object instead of an array. #423Because of the support for JSON relations the
Relationclass has changed a bit.
0.8.8
What's new
- Typing updates: #489 #487
- Improve
resultSizemethod. #213 - Avoid unnecessary updates in upsertGraph #480
0.8.7
What's new
throwIfNotFoundnow also throws when update or delete doesn't change any rows.mixinandcomposehelpers for applying multiple plugins. #475 #473- Typing updates #474 #479
upsertGraphnow validates patched models correctly. #477
0.8.6
What's new
- Finally: the first version of
upsertGraphmethod! Please open issues about bugs, WTFs and missing features. - Strip readonly virtual properties in fromJson & friends #432
- Fixed #439
0.8.5
What's new
- Add
Model.useLimitInFirstconfiguration flag.
0.8.4
What's new
- New shorthand methods
joinEager,naiveEager,mergeJoinEagerandmergeNaiveEager. - New shorthand method
findOne - New reflection method
isFindQuery - ManyToMany extra properties can now be updated #413
0.8.3
What's new
NaiveEagerAlogrithm- Aliases in relation expressions #402
- New lazily evaluated
rawfunction. #275
0.8.2
What's new
Model.namedFiltersobject for defining shared filters that can be used by name in eager expressions.- Full support for views and table aliases in eager, join, joinRelation etc. #181
- Fix
bindTransactionbug withManyToManyRelationjunction tables #395
0.8.1
What's new
throwIfNotFoundmethod for making empty query results throw an exception.- fix error when passing model instance to a
wheremethod. #387
0.8.0
What's new
- All query methods now call
Model.queryto create aQueryBuilderinstance #346 - Objection is no longer transpiled. One of the implications is that you can use a github link in package.json to test experimental versions.
countcan now be called without arguments #364- A new
getRelationsmethod for plugin development and other reflection greatness.
Breaking changes
Old model definition
function Person() {
Model.apply(this, arguments);
}
Model.extend(Person);
Person.tableName = 'Person';
Person.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
// More static and prototype methods.Easiest way to migrate to
classandextendskeywords
class Person extends Model {}
Person.tableName = 'Person';
Person.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
// More static and prototype methods.Support for node versions below 4.0.0 has been removed. With it the support for legacy class inheritance using
Model.extendmethod has also been removed. This means that you need to change your model definitions to use theclassandextendskeywords. To achieve this with the minimum amount of changes you can simply swap the constructor function andModel.extendto a class definition. You can still define all static and prototype methods and properties the old way. See the example on the right -->Note that this also affects Babel transpilation. You cannot (or need to) use
babel-plugin-transform-es2015-classesanymore. See the ESNext example project as an example of how to setup babel.The default value of
pickJsonSchemaPropertieswas changed tofalse. Before, all properties that were not listed injsonSchemawere removed beforeinsert,patchorupdate(ifjsonSchmawas defined). Starting from this version you need to explicitly set the value totrue. You may have been used this feature by accident. If you have weird problems after the update, try settingobjection.Model.pickJsonSchemaProperties = true;to see if it helps.relateandunrelatemethods now return the result of the underlying query (patchin case ofHasManyRelation,HasOneRelation, andBelongsToOneRelation.insertotherwise). Before the method input was always returned.Model.RelatedQueryBuilderis removed.Model.QueryBuilderis now used to create all query builders for the model. This only affects you if you have defined custom query builders.
0.7.12
What's new
- fix #345
0.7.11
What's new
0.7.10
What's new
- fix bugs that prevented using
$relatedQueryandeagertogether withJoinEagerAlgorithm - typing updates
0.7.9
What's new
joinRelationnow acceptsRelationExpressionsand can join multiple and nested relations.
0.7.6
What's new
rangeandpagemethods now use a window function and only generate one query on postgresql #62- fix MSSQL 2100 parameter limit in eager queries #311
0.7.5
What's new
0.7.4
What's new
- automatically select columns needed for relations #309
- fix an issue where
$formatJsonwas called insideinsertGraph#326
0.7.3
What's new
- fix #325
- fix an issue where
selecthad to be used in addition todistinctin some cases
0.7.2
What's new
HasOneThroughRelationrelation type.
0.7.1
What's new
- fix
JoinEagerAlgorithmNPE bug
0.7.0
What's new
jsonSchemawithoutpropertiesnow works. #205relationMappingscan now be a function. #227- many to many extras can now be aliased. #223
- zero values are now allowed in relation columns. #228
- active transaction can now be accessed in
$before/$afterhooks throughqueryContext.transactionproperty. - Validation can now be easily modified through a new
Validatorinterface. #241 #199 - fix a
JoinEagerproblem where an empty result for a relation caused the following relations to be empty. #292 ref(fieldExpression)syntax to reduce need for knex.raw and updating single attribute inside JSON column. #270- mergeEager method.
Breaking changes
$relatedQuerynow returns a single model instead of an array for belongsToOne and hasOne relations. #155- identifier of a model can now be updated. Be careful with this one! Before if you forgot a wrong id in an
update/patchoperation, it would simply get ignored. Now the id is also updated just like any other column #100 Table.*is now selected by default in all queries instead of*. This will break some join queries that don't have an explicit select clause. #161ValidationError.datais now an object including, for each key, a list of errors with context info. #283
0.6.2
What's new
relationMappingscan now be a function #227
0.6.1
What's new
- fix bug #205
0.6.0
What's new
- Eager loading can now be done using joins and zero extra queries. See
eagerAlgorithm,defaultEagerAlgorithmandeagerfor more info. #refin graph inserts can now contain extra properties for many-to-many relations #156#dbRefcan now be used to refer to existing rows from ainsertWithRelatedgraph.modelPathsattribute for cleaner way to point to models in relationMappings.pickJsonSchemaPropertiesconfig parameter #110insertGraphAndFetchwithinsertWithRelatedAndFetchalias. #172- Added
$beforeDeleteand$afterDeletehooks #112 - Old values can now be accessed from
$beforeUpdate,$afterUpdate,$beforeValidateand$afterValidatehooks #185 - Support length property #168
- Make sure operations are executed in the order they are called #180
- Fetch nothing if the
whereclauses hit no rows inupdate/patchAndFetchByIdmethods #189 - Lots of performance tweaks.
$loadRelatedandloadRelatednow return aQueryBuilder.
Breaking changes
Undefined values as query method arguments now throw an exception. Before they were just silently ignored and for example
delete().where('id', undefined)caused the entire table to be deleted. skipUndefined method can be called for a query builder to handle the undefined values the old way.Deprecated method
dumpSqlis now removed.$loadRelatedandloadRelatednow return aQueryBuilder. This may break your code is some rare cases where you have called a non-standard promise method likereflectfor the return value of these functions.
0.5.5
What's new
0.5.4
What's new
- bugfix: insertWithRelated now works with
additionalProperties = falseinjsonSchema - Add updateAndFetch and patchAndFetch methods for
$query - bugfix: afterGet was not called for nested models in eager query
- Use ajv instad of tv4 for json schema validation
0.5.3
What's new
- ES6 promise compatibility fixes.
0.5.1
What's new
- $afterGet hook.
0.5.0
What's new
- joinRelation family of query builder methods.
HasOneRelationfor creating inverse one-to-one relations.- Relations have been renamed
OneToOneRelation-->BelongsToOneRelation,OneToManyRelation-->HasManyRelation. The old names work, but have been deprecated. - withSchema now works as expected and sets the schema of all queries executed by the query builder the method is called for.
- filterEager method for better eager query filtering.
- extra properties feature for selecting/inserting columns from/to the join table in many-to-many relations.
- Eager query recursion depth can be controlled like so:
parent.^5.
0.4.0
What's new
- Query context feature. See #51 and these docs for more info.
- Composite key support.
- findById, deleteById, whereComposite and whereInComposite query builder methods.
Breaking changes
There shouldn't be any major breaking changes. We moved from ES5 to ES7 + babel in this version so there are big changes in the codebase. If something comes up, please open an issue.
There are a few known corner cases that may break:
You can now define a model for the join table of
ManyToManyrelations inrelationMappings. This is optional, but may be needed if you already have a model for aManyToManyrelation and you usesnake_casetocamelCaseconversion for the column names. See the documentation on the through property of relationMappings.The repo no longer contains the actual built javascript. Only the ES7 code that is transpiled when the code is published to npm. Therefore you can no longer specify a git hash to package.json to use for example the HEAD version. We will start to publish alpha and RC versions to npm when something new and experimental is added to the library.
0.3.3
What's new
- fix regression: QueryBuilder.from is broken.
0.3.2
What's new
- Improved relation expression whitespace handling.
0.3.1
What's new
whereJson*methods can now be used inside functions given towheremethods.- Added multiple missing knex methods to
QueryBuilder.
0.3.0
What's new
- insertWithRelated method for inserting model trees
- insertAndFetch, updateAndFetchById and patchAndFetchById helper methods
- Filters for eager expressions
- New alternative way to use transactions
- Many performance updates related to cloning, serializing and deserializing model trees.
Breaking changes
- QueryBuilder methods
update,patchanddeletenow return the number of affected rows. The new methodsupdateAndFetchByIdandpatchAndFetchByIdmay help with the migration modelInstance.$query()instance method now returns a single model instead of an array- Removed
Model.generateId()method.$beforeInsertcan be used instead
0.2.8
What's new
- ES6 inheritance support
- generator function support for transactions
- traverse,pick and omit methods for Model and QueryBuilder
- bugfix: issue #38
0.2.7
What's new
- bugfix: fix #37 also for
$query(). - Significant
toJson/fromJsonperformance boost.
0.2.6
What's new
- bugfix: fix regression bug that broke dumpSql.
0.2.5
What's new
- bugfix: fix regression bug that prevented values assigned to
thisin$beforecallbacks from getting into the actual database query
0.2.4
What's new
- bugfix: many-to-many relations didn't work correctly with a snake_case to camelCase conversion in the related model class.
0.2.3
What's new
- Promise constructor is now exposed through
require('objection').Promise.
0.2.2
What's new
- $beforeUpdate, $afterUpdate, $beforeInsert etc. are now asynchronous and you can return promises from them.
- Added
Model.fn()shortcut toknex.fn. - Added missing
asCallbackandnodeifymethods forQueryBuilder.
0.2.1
What's new
- bugfix: Chaining
insertwithreturningnow returns all listed columns.
0.2.0
What's new
- New name
objection.js. $beforeInsert,$afterInsert,$beforeUpdateand$afterUpdatehooks forModel.- Postgres jsonb query methods:
whereJsonEquals,whereJsonSupersetOf,whereJsonSubsetOfand friends. whereRefquery method.- Expose
knex.raw()throughModel.raw(). - Expose
knex.client.formatter()throughModel.formatter(). QueryBuildercan be used to make sub queries just like knex'sQueryBuilder.- Possibility to use a custom
QueryBuildersubclass by overridingModel.QueryBuilder. - Filter queries/objects for relations.
- A pile of bug fixes.
Breaking changes
- Project was renamed to objection.js. Migrate simply by replacing
moronwithobjection.
0.1.0
First release.