001    /*
002     * The MIT License
003     *
004     * Copyright (c) 2012-2013, Ninja Squad
005     *
006     * Permission is hereby granted, free of charge, to any person obtaining a copy
007     * of this software and associated documentation files (the "Software"), to deal
008     * in the Software without restriction, including without limitation the rights
009     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010     * copies of the Software, and to permit persons to whom the Software is
011     * furnished to do so, subject to the following conditions:
012     *
013     * The above copyright notice and this permission notice shall be included in
014     * all copies or substantial portions of the Software.
015     *
016     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
017     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
018     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
019     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
020     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
021     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
022     * THE SOFTWARE.
023     */
024    
025    package com.ninja_squad.dbsetup.operation;
026    
027    import com.ninja_squad.dbsetup.bind.Binder;
028    import com.ninja_squad.dbsetup.bind.BinderConfiguration;
029    import com.ninja_squad.dbsetup.bind.Binders;
030    import com.ninja_squad.dbsetup.generator.ValueGenerator;
031    import com.ninja_squad.dbsetup.generator.ValueGenerators;
032    import com.ninja_squad.dbsetup.util.Preconditions;
033    
034    import javax.annotation.Nonnull;
035    import javax.annotation.concurrent.Immutable;
036    import java.sql.Connection;
037    import java.sql.ParameterMetaData;
038    import java.sql.PreparedStatement;
039    import java.sql.SQLException;
040    import java.util.ArrayList;
041    import java.util.Arrays;
042    import java.util.HashMap;
043    import java.util.HashSet;
044    import java.util.Iterator;
045    import java.util.LinkedHashMap;
046    import java.util.List;
047    import java.util.Map;
048    import java.util.Set;
049    
050    /**
051     * Operation which inserts one or several rows into a table. Example usage:
052     * <pre>
053     *   Insert insert =
054     *       Insert.into("CLIENT")
055     *             .columns("CLIENT_ID", "FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "CLIENT_TYPE")
056     *             .values(1L, "John", "Doe", "1975-07-19", ClientType.NORMAL)
057     *             .values(2L, "Jack", "Smith", "1969-08-22", ClientType.HIGH_PRIORITY)
058     *             .withDefaultValue("DELETED", false)
059     *             .withDefaultValue("VERSION", 1)
060     *             .withBinder(new ClientTypeBinder(), "CLIENT_TYPE")
061     *             .build();
062     * </pre>
063     *
064     * The above operation will insert two rows inside the CLIENT table. For each row, the column DELETED will be set to
065     * <code>false</code> and the column VERSION will be set to 1. For the column CLIENT_TYPE, instead of using the
066     * {@link Binder} associated to the type of the column found in the metadata of the table, a custom binder will be used.
067     * <p>
068     * Instead of specifying values as an ordered sequence which must match the sequence of column names, some might prefer
069     * passing a map of column/value associations. This makes things more verbose, but can be more readable in some cases,
070     * when the number of columns is high. This also allows not specifying any value for columns that must stay null.
071     * The map can be constructed like any other map and passed to the builder, or it can be added using a fluent builder.
072     * The following snippet:
073     *
074     * <pre>
075     *   Insert insert =
076     *       Insert.into("CLIENT")
077     *             .columns("CLIENT_ID", "FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "CLIENT_TYPE")
078     *             .row().column("CLIENT_ID", 1L)
079     *                   .column("FIRST_NAME", "John")
080     *                   .column("LAST_NAME", "Doe")
081     *                   .column("DATE_OF_BIRTH", "1975-07-19")
082     *                   .end()
083     *             .row().column("CLIENT_ID", 2L)
084     *                   .column("FIRST_NAME", "Jack")
085     *                   .column("LAST_NAME", "Smith")
086     *                   .end() // null date of birth, because it's not in the row
087     *             .build();
088     * </pre>
089     *
090     * is thus equivalent to:
091     *
092     * <pre>
093     *   Map&lt;String, Object&gt; johnDoe = new HashMap&lt;String, Object&gt;();
094     *   johnDoe.put("CLIENT_ID", 1L);
095     *   johnDoe.put("FIRST_NAME", "John");
096     *   johnDoe.put("LAST_NAME", "Doe");
097     *   johnDoe.put("DATE_OF_BIRTH", "1975-07-19");
098     *
099     *   Map&lt;String, Object&gt; jackSmith = new HashMap&lt;String, Object&gt;();
100     *   jackSmith.put("CLIENT_ID", 2L);
101     *   jackSmith.put("FIRST_NAME", "Jack");
102     *   jackSmith.put("LAST_NAME", "Smith");
103     *
104     *   Insert insert =
105     *       Insert.into("CLIENT")
106     *             .columns("CLIENT_ID", "FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "CLIENT_TYPE")
107     *             .values(johnDoe)
108     *             .values(jackSmith)
109     *             .build();
110     * </pre>
111     *
112     * When building the Insert using column/value associations, it might seem redundant to specify the set of column names
113     * before inserting the rows. Remember, though, that all the rows of an Insert are inserted using the same
114     * parameterized SQL query. We thus need a robust and easy way to know all the columns to insert for every row of the
115     * insert. To be able to spot errors easily and early, and to avoid complex rules, the rule is thus simple: the set of
116     * columns (excluding the generated ones) is specified either by columns(), or by the columns of the first row. All the
117     * subsequent rows may not have additional columns. And <code>null</code> is inserted for all the absent columns of the
118     * subsequent rows. The above example can thus be written as
119     *
120     * <pre>
121     *   Insert insert =
122     *       Insert.into("CLIENT")
123     *             .row().column("CLIENT_ID", 1L)
124     *                   .column("FIRST_NAME", "John")
125     *                   .column("LAST_NAME", "Doe")
126     *                   .column("DATE_OF_BIRTH", "1975-07-19")
127     *                   .end()
128     *             .row().column("CLIENT_ID", 2L)
129     *                   .column("FIRST_NAME", "Jack")
130     *                   .column("LAST_NAME", "Smith")
131     *                   .end() // null date of birth, because it's not in the row
132     *             .build();
133     * </pre>
134     *
135     * but the following will throw an exception, because the DATE_OF_BIRTH column is not part of the first row:
136     *
137     * <pre>
138     *   Insert insert =
139     *       Insert.into("CLIENT")
140     *             .row().column("CLIENT_ID", 2L)
141     *                   .column("FIRST_NAME", "Jack")
142     *                   .column("LAST_NAME", "Smith")
143     *                   .column("CLIENT_TYPE", ClientType.HIGH_PRIORITY)
144     *                   .end()
145     *             .row().column("CLIENT_ID", 1L)
146     *                   .column("FIRST_NAME", "John")
147     *                   .column("LAST_NAME", "Doe")
148     *                   .column("DATE_OF_BIRTH", "1975-07-19")
149     *                   .column("CLIENT_TYPE", ClientType.NORMAL)
150     *                   .end()
151     *             .build();
152     * </pre>
153     *
154     * @author JB Nizet
155     */
156    @Immutable
157    public final class Insert implements Operation {
158        private final String table;
159        private final List<String> columnNames;
160        private final Map<String, List<Object>> generatedValues;
161        private final List<List<?>> rows;
162        private final boolean metadataUsed;
163    
164        private final Map<String, Binder> binders;
165    
166        private Insert(Builder builder) {
167            this.table = builder.table;
168            this.columnNames = builder.columnNames;
169            this.rows = builder.rows;
170            this.generatedValues = generateValues(builder.valueGenerators, rows.size());
171            this.binders = builder.binders;
172            this.metadataUsed = builder.metadataUsed;
173        }
174    
175        private Map<String, List<Object>> generateValues(Map<String, ValueGenerator<?>> valueGenerators,
176                                                          int count) {
177            Map<String, List<Object>> result = new LinkedHashMap<String, List<Object>>();
178            for (Map.Entry<String, ValueGenerator<?>> entry : valueGenerators.entrySet()) {
179                result.put(entry.getKey(), generateValues(entry.getValue(), count));
180            }
181            return result;
182        }
183    
184        private List<Object> generateValues(ValueGenerator<?> valueGenerator, int count) {
185            List<Object> result = new ArrayList<Object>(count);
186            for (int i = 0; i < count; i++) {
187                result.add(valueGenerator.nextValue());
188            }
189            return result;
190        }
191    
192        /**
193         * Inserts the values and generated values in the table. Unless <code>useMetadata</code> has been set to
194         * <code>false</code>, the given configuration is used to get the appropriate binder. Nevertheless, if a binder
195         * has explicitely been associated to a given column, this binder will always be used for this column.
196         */
197        @edu.umd.cs.findbugs.annotations.SuppressWarnings(
198            value = "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING",
199            justification = "The point here is precisely to compose a SQL String from column names coming from the user")
200        @Override
201        public void execute(Connection connection, BinderConfiguration configuration) throws SQLException {
202            List<String> allColumnNames = new ArrayList<String>(columnNames);
203            allColumnNames.addAll(generatedValues.keySet());
204    
205            String query = generateSqlQuery(allColumnNames);
206    
207            PreparedStatement stmt = connection.prepareStatement(query);
208    
209            try {
210                Map<String, Binder> usedBinders = initializeBinders(stmt, allColumnNames, configuration);
211    
212                int rowIndex = 0;
213                for (List<?> row : rows) {
214                    int i = 0;
215                    for (Object value : row) {
216                        String columnName = columnNames.get(i);
217                        Binder binder = usedBinders.get(columnName);
218                        binder.bind(stmt, i + 1, value);
219                        i++;
220                    }
221                    for (Map.Entry<String, List<Object>> entry : generatedValues.entrySet()) {
222                        String columnName = entry.getKey();
223                        List<Object> rowValues = entry.getValue();
224                        Binder binder = usedBinders.get(columnName);
225                        binder.bind(stmt, i + 1, rowValues.get(rowIndex));
226                        i++;
227                    }
228    
229                    stmt.executeUpdate();
230                    rowIndex++;
231                }
232            }
233            finally {
234                stmt.close();
235            }
236        }
237    
238        private String generateSqlQuery(List<String> allColumnNames) {
239            StringBuilder sql = new StringBuilder("insert into ").append(table).append(" (");
240            for (Iterator<String> it = allColumnNames.iterator(); it.hasNext(); ) {
241                String columnName = it.next();
242                sql.append(columnName);
243                if (it.hasNext()) {
244                    sql.append(", ");
245                }
246            }
247            sql.append(") values (");
248            for (Iterator<String> it = allColumnNames.iterator(); it.hasNext(); ) {
249                it.next();
250                sql.append("?");
251                if (it.hasNext()) {
252                    sql.append(", ");
253                }
254            }
255            sql.append(")");
256    
257            return sql.toString();
258        }
259    
260        private Map<String, Binder> initializeBinders(PreparedStatement stmt,
261                                                      List<String> allColumnNames,
262                                                      BinderConfiguration configuration) throws SQLException {
263            Map<String, Binder> result = new HashMap<String, Binder>();
264            ParameterMetaData metadata = null;
265            if (metadataUsed) {
266                try {
267                    metadata = stmt.getParameterMetaData();
268                }
269                catch (SQLException e) {
270                    metadata = null;
271                    // the parameter metadata are probably not supported by the database. Pass null to the configuration.
272                    // The default configuration will return the default binder, just as if useMetadata(false) had been used
273                }
274            }
275            int i = 1;
276            for (String columnName : allColumnNames) {
277                Binder binder = this.binders.get(columnName);
278                if (binder == null) {
279                    binder = configuration.getBinder(metadata, i);
280                    if (binder == null) {
281                        throw new IllegalStateException("null binder returned from configuration "
282                                                        + configuration.getClass());
283                    }
284                }
285                result.put(columnName, binder);
286                i++;
287            }
288            return result;
289        }
290    
291        @Override
292        public String toString() {
293            return "insert into "
294                   + table
295                   + " [columns="
296                   + columnNames
297                   + ", generatedValues="
298                   + generatedValues
299                   + ", rows="
300                   + rows
301                   + ", metadataUsed="
302                   + metadataUsed
303                   + ", binders="
304                   + binders
305                   + "]";
306    
307        }
308    
309        @Override
310        public int hashCode() {
311            final int prime = 31;
312            int result = 1;
313            result = prime * result + binders.hashCode();
314            result = prime * result + columnNames.hashCode();
315            result = prime * result + generatedValues.hashCode();
316            result = prime * result + Boolean.valueOf(metadataUsed).hashCode();
317            result = prime * result + rows.hashCode();
318            result = prime * result + table.hashCode();
319            return result;
320        }
321    
322        @Override
323        public boolean equals(Object obj) {
324            if (this == obj) {
325                return true;
326            }
327            if (obj == null) {
328                return false;
329            }
330            if (getClass() != obj.getClass()) {
331                return false;
332            }
333            Insert other = (Insert) obj;
334    
335            return binders.equals(other.binders)
336                   && columnNames.equals(other.columnNames)
337                   && generatedValues.equals(other.generatedValues)
338                   && metadataUsed == other.metadataUsed
339                   && rows.equals(other.rows)
340                   && table.equals(other.table);
341        }
342    
343        /**
344         * Creates a new Builder instance, in order to build an Insert operation into the given table
345         * @param table the name of the table to insert into
346         * @return the created Builder
347         */
348        public static Builder into(@Nonnull String table) {
349            Preconditions.checkNotNull(table, "table may not be null");
350            return new Builder(table);
351        }
352    
353        /**
354         * A builder used to create an Insert operation. Such a builder may only be used once. Once it has built its Insert
355         * operation, all its methods throw an {@link IllegalStateException}.
356         * @see Insert
357         * @see Insert#into(String)
358         * @author JB Nizet
359         */
360        public static final class Builder {
361            private final String table;
362            private final List<String> columnNames = new ArrayList<String>();
363            private final Map<String, ValueGenerator<?>> valueGenerators = new LinkedHashMap<String, ValueGenerator<?>>();
364            private final List<List<?>> rows = new ArrayList<List<?>>();
365    
366            private boolean metadataUsed = true;
367            private final Map<String, Binder> binders = new HashMap<String, Binder>();
368    
369            private boolean built;
370    
371            private Builder(String table) {
372                this.table = table;
373            }
374    
375            /**
376             * Specifies the list of columns into which values will be inserted. The values must the be specified, after,
377             * using the {@link #values(Object...)} method, or with the {@link #values(java.util.Map)} method, or by adding
378             * a row with named columns fluently using {@link #row()}.
379             * @param columns the names of the columns to insert into.
380             * @return this Builder instance, for chaining.
381             * @throws IllegalStateException if the Insert has already been built, or if this method has already been
382             * called, or if one of the given columns is also specified as one of the generated value columns, or if the
383             * set of columns has already been defined by adding a first row to the builder.
384             */
385            public Builder columns(@Nonnull String... columns) {
386                Preconditions.checkState(!built, "The insert has already been built");
387                Preconditions.checkState(columnNames.isEmpty(), "columns have already been specified");
388                for (String column : columns) {
389                    Preconditions.checkNotNull(column, "column may not be null");
390                    Preconditions.checkState(!valueGenerators.containsKey(column),
391                                             "column "
392                                                 + column
393                                                 + " has already been specified as generated value column");
394                }
395                columnNames.addAll(Arrays.asList(columns));
396                return this;
397            }
398    
399            /**
400             * Adds a row of values to insert.
401             * @param values the values to insert.
402             * @return this Builder instance, for chaining.
403             * @throws IllegalStateException if the Insert has already been built, or if the number of values doesn't match
404             * the number of columns.
405             */
406            public Builder values(@Nonnull Object... values) {
407                Preconditions.checkState(!built, "The insert has already been built");
408                Preconditions.checkArgument(values.length == columnNames.size(),
409                                            "The number of values doesn't match the number of columns");
410                rows.add(new ArrayList<Object>(Arrays.asList(values)));
411                return this;
412            }
413    
414            /**
415             * Starts building a new row with named columns to insert. If the row is the first one being added and the
416             * columns haven't been set yet by calling <code>columns()</code>, then the columns of this row constitute the
417             * column names (excluding the generated ones) of the Insert being built
418             * @return a {@link RowBuilder} instance, which, when built, will add a row to this insert builder.
419             * @throws IllegalStateException if the Insert has already been built.
420             * @see RowBuilder
421             */
422            public RowBuilder row() {
423                Preconditions.checkState(!built, "The insert has already been built");
424                return new RowBuilder(this);
425            }
426    
427            /**
428             * Adds a row to this builder. If no row has been added yet and the columns haven't been set yet by calling
429             * <code>columns()</code>, then the keys of this map constitute the column names (excluding the generated ones)
430             * of the Insert being built, in the order of the keys in the map (which is arbitrary unless an ordered or
431             * sorted map is used).
432             * @param row the row to add. The keys of the map are the column names, which must match with
433             * the column names specified in the call to {@link #columns(String...)}, or with the column names of the first
434             * added row. If a column name is not present in the map, null is inserted for this column.
435             * @return this Builder instance, for chaining.
436             * @throws IllegalStateException if the Insert has already been built.
437             * @throws IllegalArgumentException if a column name of the map doesn't match with any of the column names
438             * specified with {@link #columns(String...)}
439             */
440            public Builder values(@Nonnull Map<String, ?> row) {
441                Preconditions.checkState(!built, "The insert has already been built");
442                Preconditions.checkNotNull(row, "The row may not be null");
443    
444                boolean setColumns = rows.isEmpty() && columnNames.isEmpty();
445                if (setColumns) {
446                    columns(row.keySet().toArray(new String[row.size()]));
447                }
448                else {
449                    Set<String> rowColumnNames = new HashSet<String>(row.keySet());
450                    rowColumnNames.removeAll(columnNames);
451                    if (!rowColumnNames.isEmpty()) {
452                        throw new IllegalArgumentException(
453                            "The following columns of the row don't match with any column name: " + rowColumnNames);
454                    }
455                }
456    
457                List<Object> values = new ArrayList<Object>(columnNames.size());
458                for (String columnName : columnNames) {
459                    values.add(row.get(columnName));
460                }
461                rows.add(values);
462                return this;
463            }
464    
465            /**
466             * Associates a Binder to one or several columns.
467             * @param binder the binder to use, regardless of the metadata, for the given columns
468             * @param columns the name of the columns to associate with the given Binder
469             * @return this Builder instance, for chaining.
470             * @throws IllegalStateException if the Insert has already been built,
471             * @throws IllegalArgumentException if any of the given columns is not
472             * part of the columns or "generated value" columns.
473             */
474            public Builder withBinder(@Nonnull Binder binder, @Nonnull String... columns) {
475                Preconditions.checkState(!built, "The insert has already been built");
476                Preconditions.checkNotNull(binder, "binder may not be null");
477                for (String columnName : columns) {
478                    Preconditions.checkArgument(this.columnNames.contains(columnName)
479                                                || this.valueGenerators.containsKey(columnName),
480                                                "column "
481                                                    + columnName
482                                                    + " is not one of the registered column names");
483                    binders.put(columnName, binder);
484                }
485                return this;
486            }
487    
488            /**
489             * Specifies a default value to be inserted in a column for all the rows inserted by the Insert operation.
490             * Calling this method is equivalent to calling
491             * <code>withGeneratedValue(column, ValueGenerators.constant(value))</code>
492             * @param column the name of the column
493             * @param value the default value to insert into the column
494             * @return this Builder instance, for chaining.
495             * @throws IllegalStateException if the Insert has already been built, or if the given column is part
496             * of the columns to insert.
497             */
498            public Builder withDefaultValue(@Nonnull String column, Object value) {
499                return withGeneratedValue(column, ValueGenerators.constant(value));
500            }
501    
502            /**
503             * Allows the given column to be populated by a value generator, which will be called for every row of the
504             * Insert operation being built.
505             * @param column the name of the column
506             * @param valueGenerator the generator generating values for the given column of every row
507             * @return this Builder instance, for chaining.
508             * @throws IllegalStateException if the Insert has already been built, or if the given column is part
509             * of the columns to insert.
510             */
511            public Builder withGeneratedValue(@Nonnull String column, @Nonnull ValueGenerator<?> valueGenerator) {
512                Preconditions.checkState(!built, "The insert has already been built");
513                Preconditions.checkNotNull(column, "column may not be null");
514                Preconditions.checkNotNull(valueGenerator, "valueGenerator may not be null");
515                Preconditions.checkArgument(!columnNames.contains(column),
516                                            "column "
517                                            + column
518                                            + " is already listed in the list of column names");
519                valueGenerators.put(column, valueGenerator);
520                return this;
521            }
522    
523            /**
524             * Determines if the metadata must be used to get the appropriate binder for each inserted column (except
525             * the ones which have been associated explicitely with a Binder). The default is <code>true</code>. The insert
526             * can be faster if set to <code>false</code>, but in this case, the binder used will be the one returned
527             * by the {@link BinderConfiguration} for a null metadata (which is, by default, the
528             * {@link Binders#defaultBinder() default binder}), except the ones which have been associated explicitely with
529             * a Binder.<br/>
530             * Before version 1.3.0, a SQLException was thrown if the database doesn't support parameter metadata and
531             * <code>useMetadata(false)</code> wasn't called. Since version 1.3.0, if <code>useMetadata</code> is true
532             * (the default) but the database doesn't support metadata, then the default binder configuration returns the
533             * default binder. Using this method is thus normally unnecessary as of 1.3.0.
534             * @return this Builder instance, for chaining.
535             * @throws IllegalStateException if the Insert has already been built.
536             */
537            public Builder useMetadata(boolean useMetadata) {
538                Preconditions.checkState(!built, "The insert has already been built");
539                this.metadataUsed = useMetadata;
540                return this;
541            }
542    
543            /**
544             * Builds the Insert operation.
545             * @return the created Insert operation.
546             * @throws IllegalStateException if the Insert has already been built, or if no column and no generated value
547             * column has been specified.
548             */
549            public Insert build() {
550                Preconditions.checkState(!built, "The insert has already been built");
551                Preconditions.checkState(!this.columnNames.isEmpty() || !this.valueGenerators.isEmpty(),
552                                         "no column and no generated value column has been specified");
553                built = true;
554                return new Insert(this);
555            }
556        }
557    
558        /**
559         * A row builder, constructed with {@link com.ninja_squad.dbsetup.operation.Insert.Builder#row()}. This builder
560         * allows adding a row with named columns to an Insert:
561         *
562         * <pre>
563         *   Insert insert =
564         *       Insert.into("CLIENT")
565         *             .columns("CLIENT_ID", "FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "CLIENT_TYPE")
566         *             .row().column("CLIENT_ID", 1L)
567         *                   .column("FIRST_NAME", "John")
568         *                   .column("LAST_NAME", "Doe")
569         *                   .column("DATE_OF_BIRTH", "1975-07-19")
570         *                   .column("CLIENT_TYPE", ClientType.NORMAL)
571         *                   .end()
572         *             .row().column("CLIENT_ID", 2L)
573         *                   .column("FIRST_NAME", "Jack")
574         *                   .column("LAST_NAME", "Smith")
575         *                   .column("DATE_OF_BIRTH", "1969-08-22")
576         *                   .column("CLIENT_TYPE", ClientType.HIGH_PRIORITY)
577         *                   .end()
578         *             .build();
579         * </pre>
580         *
581         * You may omit the call to <code>columns()</code>. In that case, the columns of the Insert will be the columns
582         * specified in the first added row.
583         */
584        public static final class RowBuilder {
585            private final Builder builder;
586            private final Map<String, Object> row;
587            private boolean ended;
588    
589            private RowBuilder(Builder builder) {
590                this.builder = builder;
591                // note: very important to use a LinkedHashMap here, to guarantee the ordering of the columns.
592                this.row = new LinkedHashMap<String, Object>();
593            }
594    
595            /**
596             * Adds a new named column to the row. If a previous value has already been added for the same column, it's
597             * replaced by this new value.
598             * @param name the name of the column, which must match with a column name defined in the Insert Builder
599             * @param value the value of the column for the constructed row
600             * @return this builder, for chaining
601             * @throws IllegalArgumentException if the given name is not the name of one of the columns to insert
602             */
603            public RowBuilder column(@Nonnull String name, Object value) {
604                Preconditions.checkState(!ended, "The row has already been ended and added to the Insert Builder");
605                if (!builder.columnNames.isEmpty()) {
606                    Preconditions.checkNotNull(name, "the column name may not be null");
607                    Preconditions.checkArgument(builder.columnNames.contains(name),
608                                                "column " + name + " is not one of the registered column names");
609                }
610                row.put(name, value);
611                return this;
612            }
613    
614            /**
615             * Ends the row, adds it to the Insert Builder and returns it, for chaining.
616             * @return the Insert Builder
617             */
618            public Builder end() {
619                Preconditions.checkState(!ended, "The row has already been ended and added to the Insert Builder");
620                ended = true;
621                return builder.values(row);
622            }
623        }
624    }