001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * Florent Guillaume 011 */ 012 013package org.nuxeo.ecm.core.storage.sql.jdbc.db; 014 015import java.io.Serializable; 016import java.util.LinkedList; 017import java.util.List; 018 019import org.nuxeo.common.utils.StringUtils; 020import org.nuxeo.ecm.core.storage.sql.jdbc.dialect.Dialect; 021 022/** 023 * An {@code INSERT} statement. 024 * 025 * @author Florent Guillaume 026 */ 027public class Insert implements Serializable { 028 029 private static final long serialVersionUID = 1L; 030 031 protected final Dialect dialect; 032 033 private final Table table; 034 035 private final List<Column> columns; 036 037 private String insertValues; 038 039 public Insert(Table table) { 040 this.table = table; 041 dialect = table.getDialect(); 042 columns = new LinkedList<Column>(); 043 } 044 045 public void addColumn(Column column) { 046 columns.add(column); 047 } 048 049 public void setValues(String insertValues) { 050 this.insertValues = insertValues; 051 } 052 053 /** 054 * Gets the statement to insert a row, or copy it if {@link #setValues} has been called. 055 * <p> 056 * Example: {@code INSERT INTO foo (a, b, c) SELECT ?, b, c FROM foo WHERE 057 * id = ?} 058 * 059 * @return the SQL insert or copy statement 060 */ 061 public String getStatement() { 062 StringBuilder buf = new StringBuilder(128); 063 buf.append("INSERT INTO "); 064 buf.append(table.getQuotedName()); 065 buf.append(' '); 066 067 List<String> columnNames = new LinkedList<String>(); 068 List<String> values = new LinkedList<String>(); 069 for (Column column : columns) { 070 columnNames.add(column.getQuotedName()); 071 values.add(column.getFreeVariableSetter()); 072 } 073 074 if (columnNames.isEmpty()) { 075 buf.append(dialect.getNoColumnsInsertString()); 076 } else { 077 buf.append('('); 078 buf.append(StringUtils.join(columnNames, ", ")); 079 buf.append(") "); 080 if (insertValues == null) { 081 buf.append("VALUES ("); 082 buf.append(StringUtils.join(values, ", ")); 083 buf.append(')'); 084 } else { 085 buf.append(insertValues); 086 } 087 } 088 return buf.toString(); 089 } 090}